# Token System Setup and Usage Guide

## 🚀 Quick Setup

### 1. Database Setup
```sql
-- Run the token system database setup
mysql -u your_username -p your_database < includes/setup_token_system.sql
```

### 2. Include Token System
```php
// Add to your existing files
require_once 'includes/TokenSystem.php';
```

### 3. Basic Usage
```php
// Check if user can afford an action
if (TokenSystem::canAfford('add_participant', $user_id)) {
    // Charge for the action
    $result = TokenSystem::charge('add_participant', $user_id, ['event_id' => $event_id]);
    if ($result['success']) {
        // Continue with your logic
        addParticipant($event_id, $participant_data);
    }
}
```

## 💰 Default Token Actions

| Action | Cost | Category | Description |
|--------|------|----------|-------------|
| `add_participant` | 1 token | participants | Add a new participant to an event |
| `add_judge` | 5 tokens | judges | Add a new judge to the system |
| `create_event` | 30 tokens | events | Create a new competition event |
| `generate_pdf` | 40 tokens | reports | Generate PDF scoreboard/report |
| `send_notification` | 2 tokens | communications | Send email/SMS notification |
| `bulk_import` | 20 tokens | participants | Import multiple participants |
| `advanced_analytics` | 50 tokens | premium | Access advanced analytics |
| `custom_branding` | 100 tokens | premium | Enable custom branding |
| `api_access` | 10 tokens | integrations | External API access |

## 🎯 Integration Examples

### Quick Form Protection
```php
// Before showing expensive features
$can_create_event = TokenSystem::canAfford('create_event', $user_id);
?>
<button <?= $can_create_event ? '' : 'disabled' ?>>
    Create Event <?= $can_create_event ? '(30 tokens)' : '(Insufficient tokens)' ?>
</button>
```

### AJAX Integration
```javascript
function chargeAndPerform(action, callback) {
    $.post('/api/charge-tokens.php', {
        action: action,
        user_id: userId
    }, function(response) {
        if (response.success) {
            callback();
        } else {
            alert('Error: ' + response.message);
        }
    });
}
```

### Bulk Operations
```php
// For bulk operations, check total cost first
$participant_count = count($participants);
$total_cost = TokenSystem::getActionCost('add_participant') * $participant_count;

if (TokenSystem::getBalance($user_id) >= $total_cost) {
    foreach ($participants as $participant) {
        TokenSystem::charge('add_participant', $user_id, ['event_id' => $event_id]);
        // Add participant logic
    }
}
```

## 🎨 UI Components

### Token Balance Widget
```php
echo TokenSystem::generateWidget($user_id);
```

### Pre-check Before Actions
```php
if (!TokenSystem::canAfford('generate_pdf', $user_id)) {
    echo '<div class="alert alert-warning">
        Insufficient tokens for PDF generation. 
        <a href="/token-purchase">Purchase tokens</a>
    </div>';
}
```

## 🔧 Administration

### Access Token Management
- Navigate to `/v2/admin/token_management.php`
- Add new token actions
- Create token packages
- Manage user budgets
- View transaction history

### Adding New Actions
1. Go to Token Management → Token Actions tab
2. Click "Add New Action"
3. Fill in action details
4. Copy generated code snippet
5. Integrate into your code

### Sample Integration
```php
// Example: Charging for a custom feature
$result = TokenSystem::charge('custom_feature', $user_id, ['feature_id' => $feature_id]);
if (!$result['success']) {
    return json_encode(['error' => $result['message']]);
}

// Continue with feature logic
performCustomFeature($feature_id);

return json_encode([
    'success' => true,
    'tokens_charged' => $result['amount'],
    'remaining_balance' => TokenSystem::getBalance($user_id)
]);
```

## 📊 Monitoring and Analytics

### View Usage Statistics
```php
// Get user's transaction history
$transactions = TokenSystem::getRecentTransactions($user_id, 10);

// Get system-wide statistics
$stats = TokenSystem::getSystemStats();
```

### Budget Management
```php
// Add tokens to a user
TokenSystem::addTokens($user_id, 100, 'credit', 'Admin adjustment');

// Check if group budget is sufficient
$group_budget = TokenSystem::getGroupBudget($group_id);
```

## 🎁 Token Packages

### Default Packages
- **Starter**: 100 tokens for $10 (10% bonus)
- **Professional**: 500 tokens for $45 (12.5% bonus)
- **Enterprise**: 1000 tokens for $80 (25% bonus)
- **Premium**: 2500 tokens for $180 (44% bonus)

### Purchase Integration
```php
// After payment processing
$package = getTokenPackage($package_id);
$total_tokens = $package['token_amount'] + $package['bonus_tokens'];
TokenSystem::addTokens($user_id, $total_tokens, 'purchase', 'Package: ' . $package['name']);
```

## 🚨 Error Handling

### Graceful Degradation
```php
try {
    $result = TokenSystem::charge('action_name', $user_id);
    if (!$result['success']) {
        // Handle insufficient tokens
        return showTokenPurchasePrompt($result['message']);
    }
} catch (Exception $e) {
    // Handle system errors
    error_log('Token system error: ' . $e->getMessage());
    return showFallbackOption();
}
```

### Refund on Failure
```php
$charge_result = TokenSystem::charge('generate_pdf', $user_id);
if ($charge_result['success']) {
    try {
        // Generate PDF
        $pdf = generatePDF($data);
    } catch (Exception $e) {
        // Refund on failure
        TokenSystem::refund($charge_result['transaction_id'], 'PDF generation failed');
        throw $e;
    }
}
```

## 🔐 Security Considerations

### Validate User Permissions
```php
// Always check user permissions before charging
if (!userCanPerformAction($user_id, 'create_event')) {
    return ['success' => false, 'message' => 'Unauthorized'];
}

$result = TokenSystem::charge('create_event', $user_id);
```

### Rate Limiting
```php
// Implement rate limiting for expensive actions
if (TokenSystem::getActionUsageToday($user_id, 'api_access') > 100) {
    return ['success' => false, 'message' => 'Daily API limit exceeded'];
}
```

## 📱 Mobile Integration

### Responsive Token Widget
The token widget is fully responsive and works on mobile devices.

### Touch-Friendly Interfaces
All token management interfaces are optimized for touch devices.

## 🎯 Next Steps

1. **Test the System**: Try adding participants and see token deductions
2. **Customize Actions**: Add your own token actions for specific features
3. **Set Up Packages**: Create token packages that match your pricing strategy
4. **Monitor Usage**: Use the analytics to understand user behavior
5. **Payment Integration**: Connect with Stripe/PayPal for token purchases

## 📞 Support

For additional help:
- Check the code examples in `/includes/token_examples.php`
- Review the database schema in `/includes/setup_token_system.sql`
- Access the admin panel at `/admin/token_management.php`

---

**Happy Tokenizing! 🎉**
