# StyleScore Token Implementation Strategy

## 🎯 **Strategic Token Placement for Maximum Revenue**

This document outlines the best places to implement token-based charging in the StyleScore competition management system for optimal user value and revenue generation.

---

## 🏆 **Priority 1: High-Value Premium Features**

### **1. TV Overlay System (Premium Branding)**

**File:** `c:\stylescore2025\htdocs\v2\tv-overlay\index.php`

```php
// Add after line 15 (after database connection)
require_once '../includes/TokenSystem.php';

// Check premium overlay features
$user_id = $_SESSION['user_id'] ?? 1;
$can_use_custom_branding = TokenSystem::canAfford('custom_branding', $user_id);
$can_use_advanced_overlay = TokenSystem::canAfford('advanced_overlay', $user_id);
$can_use_broadcast_mode = TokenSystem::canAfford('tv_broadcast_mode', $user_id);

// Feature gating in UI
if (!$can_use_custom_branding) {
    $show_watermark = true;
}
```

**Token Actions:**
- `custom_branding` - **100 tokens** (remove watermarks, custom logos)
- `advanced_overlay` - **50 tokens** (advanced animations, effects)
- `tv_broadcast_mode` - **200 tokens** (professional broadcast features)

---

### **2. PDF Report Generation**

**File:** `c:\stylescore2025\htdocs\v2\admin\export_assignments_pdf.php`

```php
// Add after line 5 (after includes)
require_once '../includes/TokenSystem.php';

$user_id = $_SESSION['user_id'] ?? 1;
$result = TokenSystem::charge('generate_pdf', $user_id, [
    'event_id' => $event_id,
    'type' => 'assignments',
    'filename' => 'heat_assignments_' . date('Y-m-d')
]);

if (!$result['success']) {
    header('Content-Type: application/json');
    echo json_encode([
        'error' => $result['message'],
        'tokens_required' => TokenSystem::getActionCost('generate_pdf'),
        'current_balance' => TokenSystem::getBalance($user_id)
    ]);
    exit;
}

// Continue with PDF generation
```

**Additional PDF Files to Update:**
- `export_assignments.php`
- `live_scoreboard_3.php` (PDF export functionality)

**Token Actions:**
- `generate_pdf` - **40 tokens** (basic PDF export)
- `generate_detailed_pdf` - **80 tokens** (comprehensive reports with analytics)
- `generate_branded_pdf` - **120 tokens** (custom branded reports)

---

## 📊 **Priority 2: Core Competition Management**

### **3. Event Creation**

**File:** `c:\stylescore2025\htdocs\v2\admin\event_create.php`

```php
// Add after line 8 (after form submission check)
require_once '../includes/TokenSystem.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'] ?? 1;
    
    // Determine event complexity for pricing
    $event_type = 'basic';
    if (!empty($_POST['multi_day']) || !empty($_POST['multiple_categories'])) {
        $event_type = 'advanced';
    }
    
    $action = $event_type === 'advanced' ? 'create_multi_day_event' : 'create_event';
    
    // Check if user can afford event creation
    if (!TokenSystem::canAfford($action, $user_id)) {
        $required_tokens = TokenSystem::getActionCost($action);
        $current_balance = TokenSystem::getBalance($user_id);
        
        $message = '<div class="alert alert-danger">
            <i class="fas fa-coins"></i> Insufficient tokens to create event.<br>
            <strong>Required:</strong> ' . $required_tokens . ' tokens<br>
            <strong>Current Balance:</strong> ' . $current_balance . ' tokens<br>
            <a href="../admin/token_purchase.php" class="btn btn-primary btn-sm mt-2">
                <i class="fas fa-shopping-cart"></i> Purchase Tokens
            </a>
        </div>';
    } else {
        $charge_result = TokenSystem::charge($action, $user_id, [
            'event_name' => $_POST['name'],
            'event_date' => $_POST['date'],
            'location' => $_POST['location'],
            'sport_discipline' => $_POST['sport_discipline']
        ]);
        
        if (!$charge_result['success']) {
            $message = '<div class="alert alert-danger">' . $charge_result['message'] . '</div>';
        } else {
            // Continue with event creation logic
            $message = '<div class="alert alert-success">
                Event created successfully! 
                <strong>Tokens charged:</strong> ' . $charge_result['amount'] . '
                <strong>Remaining balance:</strong> ' . TokenSystem::getBalance($user_id) . '
            </div>';
            // ... existing event creation code
        }
    }
}
```

**Token Actions:**
- `create_event` - **30 tokens** (basic single-day event)
- `create_multi_day_event` - **75 tokens** (multi-day competitions)
- `duplicate_event` - **15 tokens** (copy existing event structure)

---

### **4. Participant Management**

**File:** `c:\stylescore2025\htdocs\v2\admin\participant_add.php`

```php
// Add after line 14 (after heats query)
require_once '../includes/TokenSystem.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'] ?? 1;
    
    try {
        // Check for bulk import
        if (isset($_POST['bulk_import']) && $_POST['bulk_import']) {
            $participant_count = count($_POST['participants']);
            $bulk_cost = TokenSystem::getActionCost('bulk_import');
            $per_participant_cost = TokenSystem::getActionCost('add_participant');
            $total_cost = $bulk_cost + ($per_participant_cost * $participant_count);
            
            if (TokenSystem::getBalance($user_id) < $total_cost) {
                throw new Exception("Insufficient tokens for bulk import of {$participant_count} participants. Required: {$total_cost} tokens");
            }
            
            $charge_result = TokenSystem::charge('bulk_import', $user_id, [
                'count' => $participant_count,
                'event_id' => $_POST['event_id']
            ]);
            
            if (!$charge_result['success']) {
                throw new Exception($charge_result['message']);
            }
            
            // Charge for each participant
            foreach ($_POST['participants'] as $participant_data) {
                TokenSystem::charge('add_participant', $user_id, [
                    'event_id' => $_POST['event_id'],
                    'participant_name' => $participant_data['name']
                ]);
            }
            
        } else {
            // Single participant
            $result = TokenSystem::charge('add_participant', $user_id, [
                'event_id' => $_POST['event_id'],
                'participant_name' => $_POST['first_name'] . ' ' . $_POST['last_name']
            ]);
            
            if (!$result['success']) {
                throw new Exception($result['message']);
            }
        }
        
        // Continue with existing participant addition logic...
        
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">' . $e->getMessage() . '</div>';
    }
}
```

**Token Actions:**
- `add_participant` - **1 token** (single participant)
- `bulk_import` - **20 tokens** (CSV/Excel import base cost)
- `participant_photo_upload` - **5 tokens** (photo management per participant)
- `edit_participant` - **0.5 tokens** (modify existing participant)

---

## 📈 **Priority 3: Advanced Analytics & Insights**

### **5. Scoring Analytics**

**File:** `c:\stylescore2025\htdocs\v2\admin\scoring_analytics.php`

```php
// Add after line 7 (after includes)
require_once '../includes/TokenSystem.php';

$user_id = $_SESSION['user_id'] ?? 1;

// Basic analytics are free, advanced require tokens
$show_advanced = false;
$analytics_error = '';

if (isset($_GET['advanced']) && $_GET['advanced'] === 'true') {
    $result = TokenSystem::charge('advanced_analytics', $user_id, [
        'analytics_type' => 'judge_performance',
        'event_id' => $_GET['event_id'] ?? null
    ]);
    
    if ($result['success']) {
        $show_advanced = true;
    } else {
        $analytics_error = '<div class="alert alert-warning">
            <i class="fas fa-chart-line"></i> Advanced Analytics Unavailable<br>
            ' . $result['message'] . '<br>
            <a href="../admin/token_purchase.php" class="btn btn-primary btn-sm">Purchase Tokens</a>
        </div>';
    }
}

// Enhanced analytics queries for premium users
if ($show_advanced) {
    // Advanced analytics with detailed judge bias analysis
    $advanced_results = $pdo->query("
        SELECT s.judge_id, u.username as judge_name, 
               COUNT(*) as total_scores,
               AVG(s.score_value) as avg_score,
               MIN(s.score_value) as min_score,
               MAX(s.score_value) as max_score,
               STDDEV(s.score_value) as std_deviation,
               -- Advanced metrics
               (SELECT AVG(score_value) FROM scores WHERE judge_id != s.judge_id) as peer_avg,
               ABS(AVG(s.score_value) - (SELECT AVG(score_value) FROM scores WHERE judge_id != s.judge_id)) as bias_score,
               COUNT(CASE WHEN s.score_value = (SELECT MAX(score_value) FROM scores WHERE participant_id = s.participant_id) THEN 1 END) as highest_scores_given
        FROM scores s
        JOIN users u ON s.judge_id = u.id
        WHERE s.status = 'OK' AND u.role = 'judge'
        GROUP BY s.judge_id, u.username
        ORDER BY bias_score ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
}
```

**Token Actions:**
- `advanced_analytics` - **50 tokens** (detailed judge analysis, bias detection)
- `export_analytics` - **25 tokens** (export analytics to Excel/CSV)
- `real_time_insights` - **30 tokens** (live competition insights)
- `predictive_analytics` - **75 tokens** (AI-powered performance predictions)

---

## 📢 **Priority 4: Communication & Notifications**

### **6. Notification System**

**File:** `c:\stylescore2025\htdocs\v2\admin\notification_api.php`

```php
// Add after line 30 (after PDO connection)
require_once '../includes/TokenSystem.php';

function sendNotification($type, $recipients, $message, $user_id, $options = []) {
    // Dynamic pricing based on notification type
    $token_costs = [
        'email' => 2,
        'sms' => 10,
        'email_bulk' => 5,
        'push_notification' => 3,
        'whatsapp' => 8,
        'automated_reminder' => 1
    ];
    
    $base_cost = $token_costs[$type] ?? 2;
    $recipient_count = is_array($recipients) ? count($recipients) : 1;
    
    // Bulk discounts
    if ($recipient_count > 50) {
        $base_cost *= 0.8; // 20% discount for bulk
    }
    if ($recipient_count > 100) {
        $base_cost *= 0.7; // 30% discount for large bulk
    }
    
    $total_cost = ceil($base_cost * $recipient_count);
    
    $result = TokenSystem::charge('send_notification', $user_id, [
        'type' => $type,
        'recipients' => $recipient_count,
        'cost' => $total_cost,
        'message_length' => strlen($message)
    ]);
    
    if (!$result['success']) {
        return [
            'success' => false, 
            'message' => $result['message'],
            'tokens_required' => $total_cost,
            'current_balance' => TokenSystem::getBalance($user_id)
        ];
    }
    
    // Continue with notification sending logic
    return ['success' => true, 'tokens_charged' => $total_cost];
}

// API endpoint for checking notification costs
if ($_GET['action'] === 'estimate_cost') {
    $type = $_GET['type'] ?? 'email';
    $recipient_count = intval($_GET['recipients'] ?? 1);
    $user_id = $_GET['user_id'] ?? 1;
    
    $estimated_cost = estimateNotificationCost($type, $recipient_count);
    $can_afford = TokenSystem::canAfford('send_notification', $user_id, $estimated_cost);
    
    echo json_encode([
        'estimated_cost' => $estimated_cost,
        'can_afford' => $can_afford,
        'current_balance' => TokenSystem::getBalance($user_id)
    ]);
    exit;
}
```

**Token Actions:**
- `send_notification` - **2-10 tokens** (varies by type)
- `automated_reminders` - **1 token** (per reminder)
- `broadcast_message` - **15 tokens** (mass communication)
- `scheduled_notifications` - **20 tokens** (time-delayed messaging)

---

## 🔌 **Priority 5: System Integration & API Access**

### **7. API Access Control**

**File:** `c:\stylescore2025\htdocs\v2\tv-overlay\api.php`

```php
// Add at the beginning after headers
require_once '../includes/TokenSystem.php';

// Rate limiting and token charging for API calls
$user_id = $_SESSION['user_id'] ?? $_GET['user_id'] ?? $_POST['user_id'] ?? null;

if (!$user_id) {
    http_response_code(401);
    echo json_encode([
        'error' => 'Authentication required',
        'message' => 'Please provide user_id parameter or valid session'
    ]);
    exit;
}

// Check API usage limits and implement tiered pricing
$daily_api_calls = TokenSystem::getActionUsageToday($user_id, 'api_access');
$endpoint = $_SERVER['REQUEST_URI'];

// Free tier: 100 calls per day
// Basic tier: 1000 calls per day (1 token per call after 100)
// Premium tier: Unlimited (10 tokens for unlimited daily access)

if ($daily_api_calls > 100) {
    if ($daily_api_calls > 1000) {
        // Require premium unlimited access
        $result = TokenSystem::charge('api_access_premium', $user_id, [
            'endpoint' => $endpoint,
            'daily_calls' => $daily_api_calls
        ]);
    } else {
        // Standard per-call charging
        $result = TokenSystem::charge('api_access', $user_id, [
            'endpoint' => $endpoint,
            'call_number' => $daily_api_calls
        ]);
    }
    
    if (!$result['success']) {
        http_response_code(429);
        echo json_encode([
            'error' => 'API limit exceeded',
            'message' => $result['message'],
            'daily_calls' => $daily_api_calls,
            'limit' => 'Free: 100/day, Paid: 1000/day, Premium: Unlimited'
        ]);
        exit;
    }
} else {
    // Free tier usage tracking (no charge)
    TokenSystem::logActivity($user_id, 'api_access_free', [
        'endpoint' => $endpoint,
        'call_number' => $daily_api_calls
    ]);
}

// Continue with API logic
```

**Token Actions:**
- `api_access` - **1 token** (per call after free limit)
- `api_access_premium` - **10 tokens** (unlimited daily access)
- `webhook_integration` - **50 tokens** (external webhook setup)
- `real_time_streaming` - **100 tokens** (live data streaming)

---

## 🏠 **Implementation Strategy**

### **Phase 1: Dashboard Integration**

**File:** `c:\stylescore2025\htdocs\v2\dashboard.php`

```php
// Add after session start
require_once 'includes/TokenSystem.php';

$user_id = $_SESSION['user_id'] ?? 1;
$token_balance = TokenSystem::getBalance($user_id);
$recent_transactions = TokenSystem::getRecentTransactions($user_id, 5);

// Feature availability checks
$features = [
    'can_create_event' => TokenSystem::canAfford('create_event', $user_id),
    'can_generate_pdf' => TokenSystem::canAfford('generate_pdf', $user_id),
    'can_use_analytics' => TokenSystem::canAfford('advanced_analytics', $user_id),
    'can_use_branding' => TokenSystem::canAfford('custom_branding', $user_id),
    'can_bulk_import' => TokenSystem::canAfford('bulk_import', $user_id)
];

// Generate token widget
$token_widget = TokenSystem::generateWidget($user_id);
```

### **Phase 2: Menu Integration**

**File:** `c:\stylescore2025\htdocs\v2\menu.php`

```php
// Add feature availability indicators
$can_create_event = TokenSystem::canAfford('create_event', $user_id);
$can_generate_pdf = TokenSystem::canAfford('generate_pdf', $user_id);
$can_use_analytics = TokenSystem::canAfford('advanced_analytics', $user_id);

// Update menu items with token indicators
echo '<li class="nav-item">
    <a class="nav-link ' . (!$can_create_event ? 'text-muted' : '') . '" href="admin/event_create.php">
        <i class="fas fa-plus-circle"></i> Create Event
        ' . (!$can_create_event ? '<span class="badge bg-warning">30 tokens</span>' : '') . '
    </a>
</li>';
```

### **Phase 3: JavaScript Integration**

**File:** `c:\stylescore2025\htdocs\v2\tv-overlay\overlay-control.js`

```javascript
// Add premium feature checking
function checkPremiumFeatures() {
    fetch('/api/check-tokens.php')
        .then(response => response.json())
        .then(data => {
            // Update UI based on token availability
            updateFeatureAvailability(data);
        })
        .catch(error => {
            console.error('Error checking token status:', error);
        });
}

function updateFeatureAvailability(tokenStatus) {
    // Custom branding
    if (!tokenStatus.can_use_custom_branding) {
        document.querySelector('.overlay-watermark').style.display = 'block';
        document.querySelector('.branding-controls').style.display = 'none';
    }
    
    // Advanced overlay features
    if (!tokenStatus.can_use_advanced_overlay) {
        document.querySelectorAll('.premium-control').forEach(el => {
            el.disabled = true;
            el.title = 'Premium feature - Requires ' + tokenStatus.advanced_overlay_cost + ' tokens';
            el.classList.add('disabled-premium');
        });
    }
    
    // Add purchase prompts
    document.querySelectorAll('.token-required').forEach(el => {
        el.addEventListener('click', function(e) {
            if (this.disabled) {
                e.preventDefault();
                showTokenPurchaseModal(this.dataset.requiredTokens);
            }
        });
    });
}

function showTokenPurchaseModal(requiredTokens) {
    const modal = document.createElement('div');
    modal.className = 'token-purchase-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <h3><i class="fas fa-coins"></i> Tokens Required</h3>
            <p>This feature requires ${requiredTokens} tokens.</p>
            <p>Current balance: <span id="current-balance"></span> tokens</p>
            <div class="modal-actions">
                <button onclick="window.open('/admin/token_purchase.php', '_blank')" class="btn btn-primary">
                    <i class="fas fa-shopping-cart"></i> Purchase Tokens
                </button>
                <button onclick="this.closest('.token-purchase-modal').remove()" class="btn btn-secondary">
                    Cancel
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    checkPremiumFeatures();
    
    // Check every 30 seconds for token balance updates
    setInterval(checkPremiumFeatures, 30000);
});
```

---

## 💰 **Token Pricing Strategy**

### **Freemium Model Tiers**

| **Tier** | **Monthly Tokens** | **Price** | **Target Users** |
|----------|-------------------|-----------|------------------|
| **Free** | 50 tokens | $0 | Individual coaches, small clubs |
| **Basic** | 200 tokens | $19/month | Growing clubs, regional competitions |
| **Professional** | 500 tokens | $49/month | Competition organizers, academies |
| **Enterprise** | 1500 tokens | $149/month | Large organizations, federations |

### **Feature Pricing Matrix**

| **Feature Category** | **Token Cost** | **Revenue Impact** | **User Value** | **Usage Frequency** |
|---------------------|---------------|-------------------|---------------|-------------------|
| **TV Overlay Premium** | 50-200 tokens | 🔴 High | 🔴 High | Low (High value) |
| **PDF Generation** | 40-80 tokens | 🟡 Medium | 🔴 High | Medium |
| **Event Creation** | 30-75 tokens | 🔴 High | 🔴 High | Low (High value) |
| **Advanced Analytics** | 25-75 tokens | 🟡 Medium | 🟡 Medium | Medium |
| **Participant Management** | 1-20 tokens | 🟢 Low | 🔴 High | High |
| **Notifications** | 2-15 tokens | 🟢 Low | 🟡 Medium | Medium |
| **API Access** | 1-10 tokens | 🟡 Medium | 🔴 High | High |

### **Revenue Optimization Strategies**

1. **High-Value, Low-Frequency Features** (TV Overlay, Event Creation)
   - Higher token costs (50-200 tokens)
   - Premium positioning
   - Focus on professional users

2. **Essential, High-Frequency Features** (Participant Management)
   - Lower token costs (1-5 tokens)
   - Volume-based revenue
   - Encourage regular usage

3. **Upsell Opportunities** (Analytics, Branding)
   - Freemium with premium upgrades
   - Clear value demonstration
   - Feature comparison tables

---

## 🚀 **Implementation Checklist**

### **Phase 1: Foundation (Week 1-2)**
- [ ] ✅ **Include TokenSystem.php** in all target files
- [ ] ✅ **Add token balance widget** to dashboard
- [ ] ✅ **Implement basic charging logic** for core features
- [ ] ✅ **Create token purchase page**
- [ ] ✅ **Add insufficient tokens error handling**

### **Phase 2: Feature Integration (Week 3-4)**
- [ ] ✅ **TV Overlay premium features** with watermark system
- [ ] ✅ **PDF generation charging** with refund on failure
- [ ] ✅ **Event creation gating** with complexity-based pricing
- [ ] ✅ **Participant management** bulk import pricing
- [ ] ✅ **API rate limiting** and tiered access

### **Phase 3: Advanced Features (Week 5-6)**
- [ ] ✅ **Advanced analytics** premium features
- [ ] ✅ **Notification system** pricing by type and volume
- [ ] ✅ **Real-time features** streaming and webhooks
- [ ] ✅ **Mobile app integration** if applicable
- [ ] ✅ **Admin token management** interface

### **Phase 4: Optimization (Week 7-8)**
- [ ] ✅ **A/B testing** pricing strategies
- [ ] ✅ **Usage analytics** and optimization
- [ ] ✅ **User feedback** integration
- [ ] ✅ **Performance monitoring** token system impact
- [ ] ✅ **Documentation** and training materials

### **Phase 5: Launch (Week 9-10)**
- [ ] ✅ **Production deployment** with monitoring
- [ ] ✅ **User migration** from free to paid features
- [ ] ✅ **Marketing campaign** for premium features
- [ ] ✅ **Customer support** for token-related issues
- [ ] ✅ **Continuous optimization** based on usage data

---

## 📊 **Success Metrics**

### **Revenue Metrics**
- Monthly Recurring Revenue (MRR) from token sales
- Average Revenue Per User (ARPU)
- Token consumption rate by feature
- Conversion rate from free to paid users

### **User Engagement Metrics**
- Feature adoption rate for premium features
- Token purchase frequency
- User retention after first token purchase
- Feature usage patterns

### **Technical Metrics**
- API response times with token checking
- System performance impact
- Error rates in token transactions
- Token system uptime

---

## 🎯 **Expected Outcomes**

### **Year 1 Projections**
- **25% of active users** upgrade to paid plans
- **$50,000+ ARR** from token sales
- **40% reduction** in support costs through self-service
- **60% increase** in feature engagement

### **Long-term Benefits**
- Sustainable revenue model
- Enhanced feature development funding
- Premium user experience differentiation
- Scalable business growth

---

## 📞 **Support & Maintenance**

### **Token System Monitoring**
- Daily transaction volume reports
- Failed transaction alerts
- User balance monitoring
- Performance impact assessment

### **User Support**
- Token purchase assistance
- Feature explanation guides
- Refund policy implementation
- Usage optimization consulting

---

**Document Version:** 1.0  
**Last Updated:** August 16, 2025  
**Next Review:** September 16, 2025

---

*This implementation strategy provides a comprehensive roadmap for monetizing the StyleScore system through strategic token placement while maintaining user value and system performance.*
