<?php
/**
 * Token System Integration Examples
 * This file demonstrates how to integrate token charging into your existing code
 */

// Example 1: Charging for adding a participant
function addParticipantWithTokens($event_id, $participant_data, $user_id) {
    // Check if user can afford the action first
    if (!TokenSystem::canAfford('add_participant', $user_id)) {
        return [
            'success' => false,
            'message' => 'Insufficient tokens. Current balance: ' . TokenSystem::getBalance($user_id) . ' tokens'
        ];
    }
    
    // Charge for the action
    $charge_result = TokenSystem::charge('add_participant', $user_id, ['event_id' => $event_id]);
    if (!$charge_result['success']) {
        return $charge_result;
    }
    
    // Continue with normal participant addition logic
    // ... your existing participant addition code here ...
    
    return [
        'success' => true,
        'message' => 'Participant added successfully. Charged: ' . $charge_result['amount'] . ' tokens'
    ];
}

// Example 2: Charging for creating an event
function createEventWithTokens($event_data, $user_id) {
    // Get the action cost first
    $action_cost = TokenSystem::getActionCost('create_event');
    $current_balance = TokenSystem::getBalance($user_id);
    
    if ($current_balance < $action_cost) {
        return [
            'success' => false,
            'message' => "Insufficient tokens. Need {$action_cost} tokens, but you only have {$current_balance} tokens.",
            'action' => 'purchase_tokens'
        ];
    }
    
    // Charge for the action
    $charge_result = TokenSystem::charge('create_event', $user_id);
    if (!$charge_result['success']) {
        return $charge_result;
    }
    
    // Create the event
    // ... your event creation logic here ...
    
    return [
        'success' => true,
        'message' => 'Event created successfully',
        'transaction_id' => $charge_result['transaction_id'],
        'remaining_balance' => TokenSystem::getBalance($user_id)
    ];
}

// Example 3: Charging for PDF generation
function generatePDFWithTokens($data, $user_id) {
    try {
        // Check and charge
        $charge_result = TokenSystem::charge('generate_pdf', $user_id, ['type' => 'scoreboard']);
        if (!$charge_result['success']) {
            return $charge_result;
        }
        
        // Generate PDF
        // ... your PDF generation logic here ...
        
        return [
            'success' => true,
            'pdf_url' => '/path/to/generated/pdf',
            'tokens_charged' => $charge_result['amount']
        ];
    } catch (Exception $e) {
        // Refund on error
        TokenSystem::refund($charge_result['transaction_id'], 'PDF generation failed');
        return [
            'success' => false,
            'message' => 'PDF generation failed: ' . $e->getMessage()
        ];
    }
}

// Example 4: Bulk operations with token checking
function bulkAddParticipants($event_id, $participants_array, $user_id) {
    $participant_count = count($participants_array);
    $cost_per_participant = TokenSystem::getActionCost('add_participant');
    $total_cost = $cost_per_participant * $participant_count;
    
    // Check if user can afford all participants
    if (!TokenSystem::getBalance($user_id) >= $total_cost) {
        return [
            'success' => false,
            'message' => "Insufficient tokens for bulk operation. Need {$total_cost} tokens for {$participant_count} participants."
        ];
    }
    
    $results = [];
    $charged_transactions = [];
    
    foreach ($participants_array as $participant) {
        // Charge for each participant
        $charge_result = TokenSystem::charge('add_participant', $user_id, ['event_id' => $event_id]);
        if (!$charge_result['success']) {
            // Refund previous charges if one fails
            foreach ($charged_transactions as $transaction_id) {
                TokenSystem::refund($transaction_id, 'Bulk operation failed');
            }
            return [
                'success' => false,
                'message' => 'Bulk operation failed. All charges refunded.'
            ];
        }
        
        $charged_transactions[] = $charge_result['transaction_id'];
        
        // Add participant logic here
        // ... your participant addition code ...
        
        $results[] = [
            'participant' => $participant,
            'success' => true,
            'transaction_id' => $charge_result['transaction_id']
        ];
    }
    
    return [
        'success' => true,
        'results' => $results,
        'total_charged' => $total_cost,
        'remaining_balance' => TokenSystem::getBalance($user_id)
    ];
}

// Example 5: Pre-check before showing UI elements
function shouldShowFeature($feature_action, $user_id) {
    return TokenSystem::canAfford($feature_action, $user_id);
}

// Example 6: Integration in HTML forms
function renderTokenizedForm($action_name, $user_id) {
    $can_afford = TokenSystem::canAfford($action_name, $user_id);
    $action_cost = TokenSystem::getActionCost($action_name);
    $balance = TokenSystem::getBalance($user_id);
    
    $html = '<div class="token-form-wrapper">';
    
    if (!$can_afford) {
        $html .= '<div class="alert alert-warning">';
        $html .= "Insufficient tokens. This action costs {$action_cost} tokens, but you only have {$balance} tokens.";
        $html .= '<a href="/token-purchase" class="btn btn-primary ms-2">Purchase Tokens</a>';
        $html .= '</div>';
    }
    
    $html .= '<form id="tokenized-form" ' . ($can_afford ? '' : 'disabled') . '>';
    $html .= '<input type="hidden" name="token_action" value="' . $action_name . '">';
    
    // ... form fields ...
    
    $html .= '<button type="submit" class="btn btn-primary" ' . ($can_afford ? '' : 'disabled') . '>';
    $html .= $can_afford ? "Submit ({$action_cost} tokens)" : "Insufficient Tokens";
    $html .= '</button>';
    $html .= '</form>';
    $html .= '</div>';
    
    return $html;
}

// Example 7: AJAX integration
function handleAjaxTokenCharge() {
    header('Content-Type: application/json');
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }
    
    $action = $_POST['action'] ?? '';
    $user_id = $_SESSION['user_id'] ?? 0;
    $reference_data = $_POST['reference_data'] ?? [];
    
    if (!$action || !$user_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required data']);
        return;
    }
    
    $result = TokenSystem::charge($action, $user_id, $reference_data);
    echo json_encode($result);
}

// Example 8: Middleware-style integration
function requireTokens($action_name) {
    return function($next) use ($action_name) {
        $user_id = $_SESSION['user_id'] ?? 0;
        
        if (!TokenSystem::canAfford($action_name, $user_id)) {
            return [
                'success' => false,
                'message' => 'Insufficient tokens for this action',
                'redirect' => '/token-purchase'
            ];
        }
        
        $charge_result = TokenSystem::charge($action_name, $user_id);
        if (!$charge_result['success']) {
            return $charge_result;
        }
        
        // Continue to next function
        $result = $next();
        
        // Add token info to result
        if (is_array($result)) {
            $result['tokens_charged'] = $charge_result['amount'];
            $result['remaining_balance'] = TokenSystem::getBalance($user_id);
        }
        
        return $result;
    };
}

// Example 9: Dashboard widget integration
function renderTokenWidget($user_id) {
    $balance = TokenSystem::getBalance($user_id);
    $recent_transactions = TokenSystem::getRecentTransactions($user_id, 5);
    
    $html = '<div class="token-widget card">';
    $html .= '<div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">';
    $html .= '<h6 class="mb-0"><i class="fas fa-coins text-warning me-2"></i>Token Balance</h6>';
    $html .= '<span class="badge bg-warning">' . number_format($balance, 2) . '</span>';
    $html .= '</div>';
    $html .= '<div class="border-0 shadow-none card-body">';
    
    if (count($recent_transactions) > 0) {
        $html .= '<h6 class="mb-2">Recent Activity</h6>';
        foreach ($recent_transactions as $transaction) {
            $icon = $transaction['transaction_type'] === 'debit' ? 'minus' : 'plus';
            $color = $transaction['transaction_type'] === 'debit' ? 'danger' : 'success';
            
            $html .= '<div class="d-flex justify-content-between align-items-center mb-1">';
            $html .= '<small>' . htmlspecialchars($transaction['description']) . '</small>';
            $html .= '<span class="text-' . $color . '">';
            $html .= '<i class="fas fa-' . $icon . ' me-1"></i>' . number_format($transaction['amount'], 2);
            $html .= '</span>';
            $html .= '</div>';
        }
    }
    
    $html .= '<a href="/token-purchase" class="btn btn-primary btn-sm w-100 mt-2">';
    $html .= '<i class="fas fa-plus me-1"></i>Purchase Tokens';
    $html .= '</a>';
    $html .= '</div>';
    $html .= '</div>';
    
    return $html;
}

// Example 10: Error handling with automatic retry
function chargeWithRetry($action, $user_id, $reference_data = [], $max_retries = 3) {
    $attempts = 0;
    
    while ($attempts < $max_retries) {
        $result = TokenSystem::charge($action, $user_id, $reference_data);
        
        if ($result['success']) {
            return $result;
        }
        
        // If it's an insufficient funds error, don't retry
        if (strpos($result['message'], 'Insufficient') !== false) {
            return $result;
        }
        
        $attempts++;
        
        // Wait a bit before retry
        if ($attempts < $max_retries) {
            usleep(100000); // 100ms
        }
    }
    
    return [
        'success' => false,
        'message' => 'Token charge failed after ' . $max_retries . ' attempts'
    ];
}

// Usage Examples in your existing files:

/*
// In your participant management page:
if ($_POST['action'] === 'add_participant') {
    $result = addParticipantWithTokens($event_id, $_POST, $user_id);
    if (!$result['success']) {
        $error_message = $result['message'];
    } else {
        $success_message = $result['message'];
    }
}

// In your event creation page:
if ($_POST['action'] === 'create_event') {
    $result = createEventWithTokens($_POST, $user_id);
    echo json_encode($result);
}

// In your dashboard:
echo renderTokenWidget($user_id);

// In your forms:
echo renderTokenizedForm('add_judge', $user_id);

// In your JavaScript:
$('#submit-form').on('click', function() {
    if (!confirm('This action will cost 5 tokens. Continue?')) return;
    
    $.post('/api/charge-tokens.php', {
        action: 'add_judge',
        reference_data: {event_id: event_id}
    }, function(response) {
        if (response.success) {
            // Continue with form submission
        } else {
            alert(response.message);
        }
    });
});

*/
?>
