# Token Management System - Complete Manual

## Table of Contents
1. [Overview](#overview)
2. [Quick Start Guide](#quick-start-guide)
3. [Token Actions Management](#token-actions-management)
4. [Token Packages Management](#token-packages-management)
5. [Budget Management](#budget-management)
6. [Code Generator](#code-generator)
7. [System Overview](#system-overview)
8. [Group Management](#group-management)
9. [PHP Backend Functions](#php-backend-functions)
10. [JavaScript Functions](#javascript-functions)
11. [Database Schema](#database-schema)
12. [API Integration](#api-integration)
13. [Troubleshooting](#troubleshooting)

---

## Overview

The Token Management System is a comprehensive credit-based system for controlling access to premium features in the Style Score platform. It provides:

- **Token Actions**: Configurable pricing for any platform feature
- **Token Packages**: Purchasable bundles with bonus tokens
- **Budget Management**: User and group-based token allocation
- **Complete Audit Trail**: Transaction logging for all token movements
- **Admin Controls**: Comprehensive management interface

---

## Quick Start Guide

### 1. Initial Setup
```bash
# 1. Run the database setup
mysql -u username -p database < includes/setup_token_system.sql

# 2. Include TokenSystem in your PHP files
include 'includes/TokenSystem.php';
```

### 2. Basic Usage
```php
// Check if user can afford an action
if (!TokenSystem::canAfford('add_participant', $user_id)) {
    echo "Insufficient tokens";
    exit;
}

// Charge tokens for an action
$result = TokenSystem::charge('add_participant', $user_id);
if (!$result['success']) {
    echo $result['message'];
    exit;
}
```

### 3. Admin Panel Access
- Navigate to: `/admin/token_management.php`
- Required role: `super_admin` or `admin`
- Features: Configure actions, packages, budgets, and view analytics

---

## Token Actions Management

### Overview
Token Actions define what activities cost tokens and how much they cost.

### Functions Available

#### Add New Action
**Button:** "Add New Action" (Blue button in Actions tab)
**Function:** Opens modal to create new token action

**Fields:**
- **Action Name**: Unique identifier (e.g., `add_participant`)
- **Description**: Human-readable description
- **Token Cost**: How many tokens this action costs
- **Category**: Grouping (participants, events, judges, etc.)
- **Reference Type**: For code generation (optional)

#### Edit Action
**Button:** Edit icon (pencil) in Actions table
**Function:** `editAction(actionId)`

**Features:**
- Pre-populated form with current values
- Cannot change action name (for system consistency)
- Can modify description, cost, category, and active status

**Usage:**
```javascript
editAction(123); // Opens edit modal for action ID 123
```

#### View Integration Code
**Button:** Code icon in Actions table
**Function:** `viewCode(actionName)`

**Features:**
- Shows multiple integration examples
- Basic usage with `TokenSystem::charge()`
- Advanced usage with reference data
- AJAX integration examples
- Copy-to-clipboard functionality

**Usage:**
```javascript
viewCode('add_participant'); // Shows code examples for this action
```

#### Delete Action
**Button:** Trash icon in Actions table
**Function:** `deleteAction(actionId)`

**Features:**
- Confirmation dialog
- Permanent deletion (cannot be undone)

**Usage:**
```javascript
deleteAction(123); // Deletes action after confirmation
```

### PHP Backend Handlers

#### handleAddAction($pdo, $data, $user_id)
Adds new token action to database with auto-generated code snippet.

#### handleEditAction($pdo, $data)
Updates existing token action properties.

#### handleDeleteAction($pdo, $data)
Removes token action from database.

---

## Token Packages Management

### Overview
Token Packages are purchasable bundles that users can buy to get tokens, often with bonus tokens included.

### Functions Available

#### Create Package
**Button:** "Create Package" (Blue button in Packages tab)
**Function:** Opens modal to create new package

**Fields:**
- **Package Name**: Display name for the package
- **Description**: What the package includes
- **Token Amount**: Base tokens included
- **Price**: Cost in real currency
- **Bonus Tokens**: Extra tokens (promotional)
- **Sort Order**: Display order

#### Edit Package
**Button:** Edit icon in package cards
**Function:** `editPackage(packageId)`

**Features:**
- Extracts current data from DOM
- Pre-populated edit form
- All fields editable

**Usage:**
```javascript
editPackage(456); // Opens edit modal for package ID 456
```

#### Delete Package
**Button:** Trash icon in package cards
**Function:** `deletePackage(packageId)`

**Features:**
- Usage validation (prevents deletion if used in transactions)
- Confirmation dialog

**Usage:**
```javascript
deletePackage(456); // Deletes package after safety checks
```

### PHP Backend Handlers

#### handleCreatePackage($pdo, $data)
Creates new token package in database.

#### handleEditPackage($pdo, $data)
Updates existing package properties.

#### handleDeletePackage($pdo, $data)
Safely removes package (checks for usage first).

---

## Budget Management

### Overview
Manages token allocation for users and groups, allowing admins to add tokens and view balances.

### Functions Available

#### Add Tokens to User
**Button:** "Add Tokens" (Blue button in Budget tab)
**Function:** Opens modal to credit user account

**Features:**
- User selection dropdown
- Amount input with validation
- Description for audit trail
- Supports both individual and group budgets

#### View User Budget
**Button:** Eye icon in user actions
**Function:** `viewUserBudget(userId)`

**Features:**
- Complete budget overview
- Transaction history
- Balance information

**Usage:**
```javascript
viewUserBudget(789); // Shows budget details for user ID 789
```

#### View Transactions
**Button:** History icon in user row
**Function:** `viewTransactions(userId)`

**Features:**
- Detailed transaction log
- Filtering capabilities
- Export options

**Usage:**
```javascript
viewTransactions(789); // Shows transaction history
```

### PHP Backend Handlers

#### handleAddTokens($pdo, $data, $user_id)
Adds tokens to user/group budget with transaction logging.

#### handleManualTokenAddition($pdo, $target_user_id, $amount, $description, $admin_user_id)
Fallback method for manual token addition with budget creation.

---

## Code Generator

### Overview
Provides ready-to-use code snippets for integrating token charging into your application.

### Features

#### Basic Integration
```php
include 'includes/TokenSystem.php';

$result = TokenSystem::charge('action_name', $user_id);
if (!$result['success']) {
    echo $result['message'];
    exit;
}
```

#### Advanced Integration with Context
```php
$result = TokenSystem::charge('action_name', $user_id, [
    'event_id' => $event_id,
    'reference_type' => 'event'
]);
```

#### Pre-checking Balance
```php
if (!TokenSystem::canAfford('action_name', $user_id)) {
    $balance = TokenSystem::getBalance($user_id);
    echo "Insufficient tokens. Current balance: $balance";
    exit;
}
```

#### AJAX Integration
```javascript
fetch('api/token_charge.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        action: 'action_name',
        user_id: userId,
        reference_data: { /* context */ }
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Tokens charged successfully');
    } else {
        alert('Error: ' + data.message);
    }
});
```

---

## System Overview

### Analytics Dashboard

#### Budget Statistics
- Total active budgets
- Total token balance across system
- Average balance per user
- Total spent in last 30 days

#### Transaction Analytics
- Transaction count and types
- Credit vs debit analysis
- Most used actions
- User activity summaries

#### Export Functions
```javascript
exportAllTransactions();    // CSV export of all transactions
exportAllBudgets();        // Excel export of all budgets
exportActionUsage();       // Action usage statistics
exportUserActivity();      // User activity report
```

---

## Group Management

### Overview
Groups allow multiple users to share a token budget, useful for organizations or teams.

### Functions Available

#### Create Group
**Button:** "Create Group" (Green button in Groups tab)
**Fields:**
- Group name and description
- Color coding
- Initial budget (optional)

#### Manage Group Members
**Function:** `manageGroupMembers(groupId)`
**Features:**
- Add/remove members
- Change member roles (owner, manager, member)
- View member activity

#### Group Budget Management
**Function:** `createGroupBudget(groupId)`
**Features:**
- Create shared budget for group
- Track group spending
- Member usage analytics

---

## PHP Backend Functions

### Core TokenSystem Class Methods

#### TokenSystem::charge($action_name, $user_id, $reference_data = [])
Charges tokens for a specific action.

**Parameters:**
- `$action_name`: The action identifier
- `$user_id`: User performing the action
- `$reference_data`: Additional context (optional)

**Returns:**
```php
[
    'success' => true/false,
    'message' => 'Success/error message',
    'transaction_id' => 123, // if successful
    'balance_after' => 45.50 // remaining balance
]
```

#### TokenSystem::canAfford($action_name, $user_id)
Checks if user has sufficient tokens.

**Returns:** `boolean`

#### TokenSystem::getBalance($user_id)
Gets current token balance for user.

**Returns:** `float` - Current balance

#### TokenSystem::addTokens($user_id, $amount, $type = 'credit', $description = '')
Adds tokens to user account.

**Parameters:**
- `$user_id`: Target user
- `$amount`: Tokens to add
- `$type`: Transaction type ('credit', 'purchase', etc.)
- `$description`: Audit description

---

## JavaScript Functions

### Action Management
```javascript
editAction(actionId)           // Edit existing action
viewCode(actionName)           // Show integration code
deleteAction(actionId)         // Delete action
copyCodeToClipboard(actionName) // Copy code snippet
```

### Package Management
```javascript
editPackage(packageId)         // Edit package details
deletePackage(packageId)       // Delete package
```

### Budget Management
```javascript
viewUserBudget(userId)         // Show user budget details
viewTransactions(userId)       // Show transaction history
addTokensToUser(userId)        // Add tokens to specific user
```

### System Functions
```javascript
refreshOverviewData()          // Reload analytics data
viewBudgetTransactions(budgetId) // Show budget-specific transactions
```

### Group Management
```javascript
viewGroupDetails(groupId)      // Show group information
manageGroupMembers(groupId)    // Manage group membership
createGroupBudget(groupId)     // Create budget for group
editGroup(groupId)             // Edit group settings
```

---

## Database Schema

### Core Tables

#### `token_actions`
```sql
- id (INT, PRIMARY KEY)
- action_name (VARCHAR, UNIQUE)
- action_description (TEXT)
- token_cost (DECIMAL)
- category (VARCHAR)
- code_snippet (TEXT)
- is_active (BOOLEAN)
- created_by (INT, FK to users)
- created_at (TIMESTAMP)
```

#### `token_packages`
```sql
- id (INT, PRIMARY KEY)
- name (VARCHAR)
- description (TEXT)
- token_amount (DECIMAL)
- price (DECIMAL)
- bonus_tokens (DECIMAL)
- sort_order (INT)
- is_active (BOOLEAN)
- created_at (TIMESTAMP)
```

#### `budgets`
```sql
- id (INT, PRIMARY KEY)
- user_id (INT, FK to users, nullable)
- group_id (INT, FK to user_groups, nullable)
- balance (DECIMAL)
- total_spent (DECIMAL)
- is_active (BOOLEAN)
- created_by (INT, FK to users)
- created_at (TIMESTAMP)
- updated_at (TIMESTAMP)
```

#### `token_transactions`
```sql
- id (INT, PRIMARY KEY)
- budget_id (INT, FK to budgets)
- action_id (INT, FK to token_actions, nullable)
- transaction_type (ENUM: 'credit', 'debit', 'purchase', 'refund')
- amount (DECIMAL)
- description (TEXT)
- reference_data (JSON)
- balance_after (DECIMAL)
- created_by (INT, FK to users)
- created_at (TIMESTAMP)
```

#### `user_groups`
```sql
- id (INT, PRIMARY KEY)
- name (VARCHAR)
- description (TEXT)
- color (VARCHAR)
- is_active (BOOLEAN)
- created_by (INT, FK to users)
- created_at (TIMESTAMP)
```

#### `user_group_memberships`
```sql
- id (INT, PRIMARY KEY)
- user_id (INT, FK to users)
- group_id (INT, FK to user_groups)
- role_in_group (ENUM: 'owner', 'manager', 'member')
- added_by (INT, FK to users)
- joined_at (TIMESTAMP)
```

---

## API Integration

### Charging Tokens via API
Create endpoint: `api/token_charge.php`

```php
<?php
include '../includes/TokenSystem.php';

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'];
$user_id = $input['user_id'];
$reference_data = $input['reference_data'] ?? [];

$result = TokenSystem::charge($action, $user_id, $reference_data);

header('Content-Type: application/json');
echo json_encode($result);
?>
```

### Getting Balance via API
```php
$balance = TokenSystem::getBalance($user_id);
echo json_encode(['balance' => $balance]);
```

---

## Troubleshooting

### Common Issues

#### "Insufficient tokens" Error
**Cause:** User doesn't have enough tokens for the action
**Solution:** 
1. Check user balance: `TokenSystem::getBalance($user_id)`
2. Add tokens via admin panel
3. Verify action cost is reasonable

#### "Action not found" Error
**Cause:** Action name doesn't exist in database
**Solution:**
1. Check `token_actions` table
2. Add action via admin panel
3. Verify action name spelling

#### Budget Not Found
**Cause:** User doesn't have an active budget
**Solution:**
1. Create budget via admin panel
2. Add user to a group with budget
3. Check budget `is_active` status

#### JavaScript Function Errors
**Cause:** Missing Bootstrap or jQuery dependencies
**Solution:**
1. Verify Bootstrap 5 is loaded
2. Check browser console for errors
3. Ensure proper modal initialization

### Debug Mode
Enable debug mode in TokenSystem:
```php
TokenSystem::setDebugMode(true);
```

### Logging
All transactions are automatically logged in `token_transactions` table for audit purposes.

---

## Support

For additional support:
1. Check the troubleshooting section above
2. Review the PHP error logs
3. Verify database connectivity
4. Ensure proper user permissions

## Version Information
- **Version:** 2.0
- **Last Updated:** August 2025
- **Compatibility:** PHP 7.4+, MySQL 5.7+, Bootstrap 5+
