<?php
// Token Management Panel
include '../includes/auth.php';
include '../includes/db.php';
include '../includes/TokenSystem.php';

// Check if user has permission
$allowed_roles = ['super_admin', 'admin'];
$user_role = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';

if (!in_array($user_role, $allowed_roles)) {
    header("Location: ../login.php?error=unauthorized");
    exit;
}

$message = '';
$current_user_id = $_SESSION['user_id'] ?? 0;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_action':
                $message = handleAddAction($pdo, $_POST, $current_user_id);
                break;
            case 'edit_action':
                $message = handleEditAction($pdo, $_POST);
                break;
            case 'delete_action':
                $message = handleDeleteAction($pdo, $_POST);
                break;
            case 'add_tokens':
                $message = handleAddTokens($pdo, $_POST, $current_user_id);
                break;
            case 'create_package':
                $message = handleCreatePackage($pdo, $_POST);
                break;
            case 'create_group':
                $message = handleCreateGroup($pdo, $_POST, $current_user_id);
                break;
            case 'add_member':
                $message = handleAddMember($pdo, $_POST, $current_user_id);
                break;
        }
        
        if (strpos($message, 'success') === 0) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?msg=" . urlencode($message));
            exit;
        }
    }
}

// Handle GET messages
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
}

function handleAddAction($pdo, $data, $user_id) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO token_actions (action_name, action_description, token_cost, category, code_snippet, created_by)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $code_snippet = "TokenSystem::charge('{$data['action_name']}', \$user_id, ['{$data['reference_type']}' => \${$data['reference_type']}]);";
        
        $stmt->execute([
            $data['action_name'],
            $data['action_description'],
            $data['token_cost'],
            $data['category'],
            $code_snippet,
            $user_id
        ]);
        
        return "success: Action '{$data['action_name']}' added successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleEditAction($pdo, $data) {
    try {
        $stmt = $pdo->prepare("
            UPDATE token_actions 
            SET action_description = ?, token_cost = ?, category = ?, is_active = ?
            WHERE id = ?
        ");
        
        $stmt->execute([
            $data['action_description'],
            $data['token_cost'],
            $data['category'],
            isset($data['is_active']) ? 1 : 0,
            $data['action_id']
        ]);
        
        return "success: Action updated successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleDeleteAction($pdo, $data) {
    try {
        $stmt = $pdo->prepare("DELETE FROM token_actions WHERE id = ?");
        $stmt->execute([$data['action_id']]);
        return "success: Action deleted successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleAddTokens($pdo, $data, $user_id) {
    try {
        $target_user_id = intval($data['target_user_id']);
        $amount = floatval($data['amount']);
        $description = $data['description'] ?? 'Admin credit adjustment';
        
        if ($amount <= 0) {
            return "error: Amount must be greater than 0";
        }
        
        // Check if user exists
        $user_check = $pdo->prepare("SELECT username FROM users WHERE id = ?");
        $user_check->execute([$target_user_id]);
        $target_user = $user_check->fetch();
        
        if (!$target_user) {
            return "error: Target user not found";
        }
        
        // Try to add tokens using TokenSystem
        try {
            $result = TokenSystem::addTokens($target_user_id, $amount, 'credit', $description);
            if ($result['success']) {
                return "success: " . $result['message'];
            } else {
                // If TokenSystem fails, try manual budget creation/update
                return handleManualTokenAddition($pdo, $target_user_id, $amount, $description, $user_id);
            }
        } catch (Exception $e) {
            // If TokenSystem fails, try manual approach
            return handleManualTokenAddition($pdo, $target_user_id, $amount, $description, $user_id);
        }
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleManualTokenAddition($pdo, $target_user_id, $amount, $description, $admin_user_id) {
    try {
        // Find or create budget for user
        $budget_id = null;
        
        // Try to find existing budget through group membership
        $budget_stmt = $pdo->prepare("
            SELECT b.id, b.balance 
            FROM budgets b
            LEFT JOIN user_group_memberships ugm ON b.group_id = ugm.group_id
            WHERE ugm.user_id = ? AND b.is_active = 1
            LIMIT 1
        ");
        $budget_stmt->execute([$target_user_id]);
        $budget = $budget_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($budget) {
            $budget_id = $budget['id'];
            $current_balance = floatval($budget['balance']);
        } else {
            // Try direct budget lookup
            $direct_budget_stmt = $pdo->prepare("
                SELECT id, balance FROM budgets WHERE user_id = ? AND is_active = 1 LIMIT 1
            ");
            $direct_budget_stmt->execute([$target_user_id]);
            $direct_budget = $direct_budget_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($direct_budget) {
                $budget_id = $direct_budget['id'];
                $current_balance = floatval($direct_budget['balance']);
            } else {
                // Create new budget - try group-based first
                try {
                    // Check if user is in a group
                    $group_stmt = $pdo->prepare("
                        SELECT group_id FROM user_group_memberships WHERE user_id = ? LIMIT 1
                    ");
                    $group_stmt->execute([$target_user_id]);
                    $group_result = $group_stmt->fetch();
                    
                    if ($group_result) {
                        // Create group budget - check if group exists first
                        $group_check = $pdo->prepare("SELECT id FROM user_groups WHERE id = ?");
                        $group_check->execute([$group_result['group_id']]);
                        if ($group_check->fetch()) {
                            $create_budget_stmt = $pdo->prepare("
                                INSERT INTO budgets (group_id, balance, total_spent, is_active, created_by) 
                                VALUES (?, 0, 0, 1, ?)
                            ");
                            $create_budget_stmt->execute([$group_result['group_id'], $admin_user_id]);
                            $budget_id = $pdo->lastInsertId();
                            $current_balance = 0;
                        } else {
                            // Group doesn't exist, create user-specific budget instead
                            $create_budget_stmt = $pdo->prepare("
                                INSERT INTO budgets (user_id, balance, total_spent, is_active, created_by) 
                                VALUES (?, 0, 0, 1, ?)
                            ");
                            $create_budget_stmt->execute([$target_user_id, $admin_user_id]);
                            $budget_id = $pdo->lastInsertId();
                            $current_balance = 0;
                        }
                    } else {
                        // Create user-specific budget
                        $create_budget_stmt = $pdo->prepare("
                            INSERT INTO budgets (user_id, balance, total_spent, is_active, created_by) 
                            VALUES (?, 0, 0, 1, ?)
                        ");
                        $create_budget_stmt->execute([$target_user_id, $admin_user_id]);
                        $budget_id = $pdo->lastInsertId();
                        $current_balance = 0;
                    }
                } catch (Exception $e) {
                    return "error: Unable to create budget: " . $e->getMessage();
                }
            }
        }
        
        // Update budget balance
        $new_balance = $current_balance + $amount;
        $update_budget_stmt = $pdo->prepare("
            UPDATE budgets SET balance = ?, updated_at = NOW() WHERE id = ?
        ");
        $update_budget_stmt->execute([$new_balance, $budget_id]);
        
        // Log transaction
        try {
            $log_stmt = $pdo->prepare("
                INSERT INTO token_transactions 
                (budget_id, transaction_type, amount, description, balance_after, created_by) 
                VALUES (?, 'credit', ?, ?, ?, ?)
            ");
            $log_stmt->execute([$budget_id, $amount, $description, $new_balance, $admin_user_id]);
        } catch (Exception $e) {
            // Transaction logging failed, but budget update succeeded
        }
        
        return "success: Added {$amount} tokens successfully. New balance: {$new_balance}";
        
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleCreatePackage($pdo, $data) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO token_packages (name, description, token_amount, price, bonus_tokens, sort_order)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $data['package_name'],
            $data['package_description'],
            $data['token_amount'],
            $data['price'],
            $data['bonus_tokens'] ?? 0,
            $data['sort_order'] ?? 0
        ]);
        
        return "success: Token package created successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleCreateGroup($pdo, $data, $user_id) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO user_groups (name, description, color, created_by)
            VALUES (?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $data['group_name'],
            $data['group_description'],
            $data['group_color'],
            $user_id
        ]);
        
        $group_id = $pdo->lastInsertId();
        
        // Add creator as owner of the group
        $member_stmt = $pdo->prepare("
            INSERT INTO user_group_memberships (user_id, group_id, role_in_group, added_by)
            VALUES (?, ?, 'owner', ?)
        ");
        $member_stmt->execute([$user_id, $group_id, $user_id]);
        
        // Create initial budget if specified
        if (!empty($data['initial_budget']) && $data['initial_budget'] > 0) {
            $budget_stmt = $pdo->prepare("
                INSERT INTO budgets (group_id, balance, total_spent, is_active, created_by)
                VALUES (?, ?, 0, 1, ?)
            ");
            $budget_stmt->execute([$group_id, $data['initial_budget'], $user_id]);
        }
        
        return "success: Group '{$data['group_name']}' created successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleAddMember($pdo, $data, $user_id) {
    try {
        // Check if user is already in the group
        $check_stmt = $pdo->prepare("
            SELECT id FROM user_group_memberships 
            WHERE user_id = ? AND group_id = ?
        ");
        $check_stmt->execute([$data['user_id'], $data['group_id']]);
        
        if ($check_stmt->fetch()) {
            return "error: User is already a member of this group";
        }
        
        // Add user to group
        $stmt = $pdo->prepare("
            INSERT INTO user_group_memberships (user_id, group_id, role_in_group, added_by)
            VALUES (?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $data['user_id'],
            $data['group_id'],
            $data['role_in_group'],
            $user_id
        ]);
        
        // Get user and group names for success message
        $user_stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
        $user_stmt->execute([$data['user_id']]);
        $username = $user_stmt->fetchColumn();
        
        $group_stmt = $pdo->prepare("SELECT name FROM user_groups WHERE id = ?");
        $group_stmt->execute([$data['group_id']]);
        $group_name = $group_stmt->fetchColumn();
        
        return "success: User '{$username}' added to group '{$group_name}' as {$data['role_in_group']}";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

// Fetch data
try {
    // Get all actions
    $actions = $pdo->query("
        SELECT ta.*, u.username as created_by_name
        FROM token_actions ta
        LEFT JOIN users u ON ta.created_by = u.id
        ORDER BY ta.category, ta.action_name
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all packages
    $packages = $pdo->query("
        SELECT * FROM token_packages
        ORDER BY sort_order, price
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get budget statistics
    $budget_stats = $pdo->query("
        SELECT 
            COUNT(*) as total_budgets,
            SUM(balance) as total_balance,
            SUM(total_spent) as total_spent,
            AVG(balance) as avg_balance
        FROM budgets
        WHERE is_active = 1
    ")->fetch(PDO::FETCH_ASSOC);
    
    // Get transaction statistics
    $transaction_stats = $pdo->query("
        SELECT 
            COUNT(*) as total_transactions,
            SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) as total_debits,
            SUM(CASE WHEN transaction_type IN ('credit', 'purchase') THEN amount ELSE 0 END) as total_credits
        FROM token_transactions
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ")->fetch(PDO::FETCH_ASSOC);
    
    // Get all users for token management
    $users = $pdo->query("
        SELECT u.id, u.username, p.full_name, b.balance
        FROM users u
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN user_group_memberships ugm ON u.id = ugm.user_id
        LEFT JOIN budgets b ON ugm.group_id = b.group_id
        WHERE u.role != 'participant'
        ORDER BY p.full_name, u.username
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all budgets for overview
    $all_budgets = $pdo->query("
        SELECT 
            b.*,
            g.name as group_name,
            g.color as group_color,
            COUNT(ugm.user_id) as member_count,
            u.username as owner_username,
            p.full_name as owner_name,
            cb.username as created_by_name
        FROM budgets b
        LEFT JOIN user_groups g ON b.group_id = g.id
        LEFT JOIN user_group_memberships ugm ON g.id = ugm.group_id
        LEFT JOIN users u ON b.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN users cb ON b.created_by = cb.id
        GROUP BY b.id
        ORDER BY b.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all transactions for overview (last 100)
    $all_transactions = $pdo->query("
        SELECT 
            tt.*,
            ta.action_name,
            COALESCE(gu.username, bu.username) as budget_owner,
            COALESCE(gu.id, bu.id) as budget_owner_id,
            cb.username as created_by_name,
            cb.role as created_by_role,
            cb.id as created_by_id
        FROM token_transactions tt
        LEFT JOIN token_actions ta ON tt.action_id = ta.id
        LEFT JOIN budgets b ON tt.budget_id = b.id
        LEFT JOIN user_groups g ON b.group_id = g.id
        LEFT JOIN user_group_memberships ugm ON g.id = ugm.group_id
        LEFT JOIN users gu ON ugm.user_id = gu.id
        LEFT JOIN users bu ON b.user_id = bu.id
        LEFT JOIN users cb ON tt.created_by = cb.id
        ORDER BY tt.created_at DESC
        LIMIT 100
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get action usage statistics
    $action_usage = $pdo->query("
        SELECT 
            ta.action_name,
            ta.category,
            ta.token_cost,
            COUNT(tt.id) as usage_count,
            SUM(tt.amount) as total_tokens,
            AVG(tt.amount) as avg_cost
        FROM token_actions ta
        LEFT JOIN token_transactions tt ON ta.id = tt.action_id
        WHERE tt.transaction_type = 'debit'
        GROUP BY ta.id
        HAVING usage_count > 0
        ORDER BY usage_count DESC, total_tokens DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get user activity summary
    $user_activity = $pdo->query("
        SELECT 
            u.username,
            p.full_name,
            COUNT(tt.id) as transaction_count,
            SUM(CASE WHEN tt.transaction_type = 'debit' THEN tt.amount ELSE 0 END) as total_spent,
            COALESCE(b.balance, 0) as current_balance
        FROM users u
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN user_group_memberships ugm ON u.id = ugm.user_id
        LEFT JOIN budgets b ON (ugm.group_id = b.group_id OR u.id = b.user_id)
        LEFT JOIN token_transactions tt ON b.id = tt.budget_id
        WHERE u.role != 'participant'
        GROUP BY u.id
        HAVING transaction_count > 0
        ORDER BY total_spent DESC, transaction_count DESC
        LIMIT 20
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all groups with member details
    $all_groups = $pdo->query("
        SELECT 
            g.*,
            COUNT(ugm.user_id) as member_count,
            GROUP_CONCAT(CONCAT(COALESCE(p.full_name, u.username), ' (', ugm.role_in_group, ')') SEPARATOR ', ') as members_list,
            b.balance as group_budget,
            b.id as budget_id,
            cb.username as created_by_name
        FROM user_groups g
        LEFT JOIN user_group_memberships ugm ON g.id = ugm.group_id
        LEFT JOIN users u ON ugm.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN budgets b ON g.id = b.group_id AND b.is_active = 1
        LEFT JOIN users cb ON g.created_by = cb.id
        WHERE g.is_active = 1
        GROUP BY g.id
        ORDER BY g.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get detailed group memberships for management
    $group_memberships = $pdo->query("
        SELECT 
            g.id as group_id,
            g.name as group_name,
            g.color as group_color,
            u.id as user_id,
            u.username,
            p.full_name,
            ugm.role_in_group,
            ugm.joined_at,
            ab.username as added_by_name
        FROM user_groups g
        INNER JOIN user_group_memberships ugm ON g.id = ugm.group_id
        INNER JOIN users u ON ugm.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN users ab ON ugm.added_by = ab.id
        WHERE g.is_active = 1
        ORDER BY g.name, ugm.role_in_group DESC, p.full_name, u.username
    ")->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $actions = [];
    $packages = [];
    $budget_stats = ['total_budgets' => 0, 'total_balance' => 0, 'total_spent' => 0, 'avg_balance' => 0];
    $transaction_stats = ['total_transactions' => 0, 'total_debits' => 0, 'total_credits' => 0];
    $users = [];
    $all_budgets = [];
    $all_transactions = [];
    $action_usage = [];
    $user_activity = [];
    $all_groups = [];
    $group_memberships = [];
    if (!$message) {
        $message = "error: Database error: " . $e->getMessage();
    }
}

// Helper function for category colors
function getCategoryColor($category) {
    $colors = [
        'participants' => 'primary',
        'events' => 'success', 
        'judges' => 'info',
        'reports' => 'warning',
        'communications' => 'secondary',
        'premium' => 'danger',
        'scoring' => 'dark',
        'general' => 'light'
    ];
    return $colors[$category] ?? 'secondary';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Token Management - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <div class="row">
            <div class="col-12">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="mb-1">
                            <i class="fas fa-coins text-warning me-2"></i>Token Management
                        </h2>
                        <p class="text-muted mb-0">Manage credits, pricing, and budget controls</p>
                    </div>
                    <span class="badge bg-warning fs-6">Total Balance: <?= number_format($budget_stats['total_balance'], 2) ?> tokens</span>
                </div>

                <!-- Messages -->
                <?php if ($message): ?>
                    <?php
                    $msg_type = strpos($message, 'success:') === 0 ? 'success' : 'danger';
                    $msg_text = substr($message, strpos($message, ':') + 1);
                    ?>
                    <div class="alert alert-<?= $msg_type ?> alert-dismissible fade show">
                        <i class="fas fa-<?= $msg_type === 'success' ? 'check-circle' : 'exclamation-triangle' ?> me-2"></i>
                        <?= htmlspecialchars(trim($msg_text)) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row g-3 mb-4">
                    <div class="col-lg-3 col-md-6">
                        <div class="border-0 shadow-none card border-warning">
                            <div class="border-0 shadow-none card-body text-center">
                                <i class="fas fa-coins fa-2x text-warning mb-2"></i>
                                <h4 class="mb-1"><?= number_format($budget_stats['total_balance'], 0) ?></h4>
                                <p class="text-muted mb-0">Total Tokens</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="border-0 shadow-none card border-primary">
                            <div class="border-0 shadow-none card-body text-center">
                                <i class="fas fa-tasks fa-2x text-primary mb-2"></i>
                                <h4 class="mb-1"><?= count($actions) ?></h4>
                                <p class="text-muted mb-0">Active Actions</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="border-0 shadow-none card border-success">
                            <div class="border-0 shadow-none card-body text-center">
                                <i class="fas fa-exchange-alt fa-2x text-success mb-2"></i>
                                <h4 class="mb-1"><?= number_format($transaction_stats['total_transactions']) ?></h4>
                                <p class="text-muted mb-0">Transactions (30d)</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="border-0 shadow-none card border-info">
                            <div class="border-0 shadow-none card-body text-center">
                                <i class="fas fa-chart-line fa-2x text-info mb-2"></i>
                                <h4 class="mb-1"><?= number_format($budget_stats['avg_balance'], 1) ?></h4>
                                <p class="text-muted mb-0">Avg Balance</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Main Content Tabs -->
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header p-0">
                        <ul class="nav nav-tabs card-header-tabs" id="tokenTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="actions-tab" data-bs-toggle="tab" data-bs-target="#actions" type="button" role="tab">
                                    <i class="fas fa-tasks me-2"></i>Token Actions
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="packages-tab" data-bs-toggle="tab" data-bs-target="#packages" type="button" role="tab">
                                    <i class="fas fa-box me-2"></i>Token Packages
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="budgets-tab" data-bs-toggle="tab" data-bs-target="#budgets" type="button" role="tab">
                                    <i class="fas fa-wallet me-2"></i>Budget Management
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="code-tab" data-bs-toggle="tab" data-bs-target="#code" type="button" role="tab">
                                    <i class="fas fa-code me-2"></i>Code Generator
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button" role="tab">
                                    <i class="fas fa-chart-pie me-2"></i>System Overview
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="groups-tab" data-bs-toggle="tab" data-bs-target="#groups" type="button" role="tab">
                                    <i class="fas fa-users me-2"></i>Group Members
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="help-tab" data-bs-toggle="tab" data-bs-target="#help" type="button" role="tab">
                                    <i class="fas fa-question-circle me-2"></i>Help & Documentation
                                </button>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="border-0 shadow-none card-body">
                        <div class="tab-content" id="tokenTabsContent">
                        <!-- Token Actions Tab -->
                        <div class="tab-pane fade show active" id="actions" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="mb-0">Token Actions Configuration</h5>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addActionModal">
                                    <i class="fas fa-plus me-2"></i>Add New Action
                                </button>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Action</th>
                                            <th>Description</th>
                                            <th>Cost</th>
                                            <th>Category</th>
                                            <th>Status</th>
                                            <th>Created By</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($actions as $action): ?>
                                        <tr>
                                            <td>
                                                <code class="text-primary"><?= htmlspecialchars($action['action_name']) ?></code>
                                            </td>
                                            <td><?= htmlspecialchars($action['action_description']) ?></td>
                                            <td>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="fas fa-coins me-1"></i><?= number_format($action['token_cost'], 2) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?= getCategoryColor($action['category']) ?>">
                                                    <?= ucfirst($action['category']) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <i class="fas fa-circle text-<?= $action['is_active'] ? 'success' : 'danger' ?>"></i>
                                                <?= $action['is_active'] ? 'Active' : 'Inactive' ?>
                                            </td>
                                            <td>
                                                <small><?= htmlspecialchars($action['created_by_name'] ?: 'System') ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-primary" onclick="editAction(<?= $action['id'] ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-info" onclick="viewCode('<?= htmlspecialchars($action['action_name']) ?>')">
                                                        <i class="fas fa-code"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" onclick="deleteAction(<?= $action['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <!-- Token Packages Tab -->
                        <div class="tab-pane fade" id="packages" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="mb-0">Token Purchase Packages</h5>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPackageModal">
                                    <i class="fas fa-plus me-2"></i>Create Package
                                </button>
                            </div>
                            
                            <div class="row g-4">
                                <?php foreach ($packages as $package): ?>
                                <div class="col-lg-3 col-md-6">
                                    <div class="border-0 shadow-none card h-100 border">
                                        <div class="border-0 shadow-none card-header text-center">
                                            <h6 class="mb-0 text-primary"><?= htmlspecialchars($package['name']) ?></h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body text-center">
                                            <div class="display-6 text-primary mb-2">
                                                $<?= number_format($package['price'], 2) ?>
                                            </div>
                                            <div class="badge bg-warning text-dark mb-3">
                                                <?= number_format($package['token_amount']) ?> tokens
                                            </div>
                                            <?php if ($package['bonus_tokens'] > 0): ?>
                                                <div class="badge bg-success mb-3">
                                                    +<?= number_format($package['bonus_tokens']) ?> bonus
                                                </div>
                                            <?php endif; ?>
                                            <p class="text-muted small"><?= htmlspecialchars($package['description']) ?></p>
                                        </div>
                                        <div class="border-0 shadow-none card-footer">
                                            <div class="btn-group w-100">
                                                <button class="btn btn-outline-primary btn-sm" onclick="editPackage(<?= $package['id'] ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-danger btn-sm" onclick="deletePackage(<?= $package['id'] ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Budget Management Tab -->
                        <div class="tab-pane fade" id="budgets" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="mb-0">User Budget Management</h5>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTokensModal">
                                    <i class="fas fa-plus me-2"></i>Add Tokens
                                </button>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>User</th>
                                            <th>Current Balance</th>
                                            <th>Recent Activity</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td>
                                                <div>
                                                    <h6 class="mb-0"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?></h6>
                                                    <small class="text-muted">@<?= htmlspecialchars($user['username']) ?></small>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?= $user['balance'] > 50 ? 'success' : ($user['balance'] > 10 ? 'warning' : 'danger') ?> fs-6">
                                                    <?= number_format($user['balance'] ?: 0, 2) ?> tokens
                                                </span>
                                            </td>
                                            <td>
                                                <button class="btn btn-outline-info btn-sm" onclick="viewTransactions(<?= $user['id'] ?>)">
                                                    <i class="fas fa-history me-1"></i>View History
                                                </button>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-success" onclick="addTokensToUser(<?= $user['id'] ?>)">
                                                        <i class="fas fa-plus"></i>
                                                    </button>
                                                    <button class="btn btn-outline-primary" onclick="viewUserBudget(<?= $user['id'] ?>)">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <!-- Code Generator Tab -->
                        <div class="tab-pane fade" id="code" role="tabpanel">
                            <h5 class="mb-4">Integration Code Generator</h5>
                            
                            <div class="row g-4">
                                <div class="col-lg-6">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header">
                                            <h6 class="mb-0">
                                                <i class="fas fa-code me-2"></i>Basic Usage
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <p class="text-muted">Include this at the top of your files:</p>
                                            <pre class="bg-light border rounded p-3"><code>include 'includes/TokenSystem.php';</code></pre>
                                            
                                            <p class="text-muted mt-3">Charge for an action:</p>
                                            <pre class="bg-light border rounded p-3"><code>$result = TokenSystem::charge('action_name', $user_id, ['event_id' => $event_id]);
if (!$result['success']) {
    // Handle insufficient tokens
    echo $result['message'];
    return;
}</code></pre>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-lg-6">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header">
                                            <h6 class="mb-0">
                                                <i class="fas fa-shield-check me-2"></i>Pre-check Balance
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <p class="text-muted">Check before performing action:</p>
                                            <pre class="bg-light border rounded p-3"><code>if (!TokenSystem::canAfford('action_name', $user_id)) {
    $balance = TokenSystem::getBalance($user_id);
    echo "Insufficient tokens. Balance: $balance";
    return;
}</code></pre>
                                            
                                            <p class="text-muted mt-3">Get widget for UI:</p>
                                            <pre class="bg-light border rounded p-3"><code>echo TokenSystem::generateWidget($user_id);</code></pre>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <div class="border-0 shadow-none card">
                                    <div class="border-0 shadow-none card-header">
                                        <h6 class="mb-0">
                                            <i class="fas fa-magic me-2"></i>Action-Specific Code Snippets
                                        </h6>
                                    </div>
                                    <div class="border-0 shadow-none card-body">
                                        <div class="row">
                                            <?php 
                                            $categories = array_unique(array_column($actions, 'category'));
                                            foreach ($categories as $category): 
                                                $cat_actions = array_filter($actions, function($a) use ($category) { return $a['category'] === $category; });
                                            ?>
                                            <div class="col-lg-6 mb-4">
                                                <h6 class="text-<?= getCategoryColor($category) ?>">
                                                    <i class="fas fa-tag me-1"></i><?= ucfirst($category) ?>
                                                </h6>
                                                <?php foreach ($cat_actions as $action): ?>
                                                <div class="mb-2">
                                                    <small class="text-muted d-block"><?= htmlspecialchars($action['action_name']) ?> (<?= $action['token_cost'] ?> tokens)</small>
                                                    <pre class="bg-light border rounded p-2 small"><code><?= htmlspecialchars($action['code_snippet']) ?></code></pre>
                                                </div>
                                                <?php endforeach; ?>
                                            </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- System Overview Tab -->
                        <div class="tab-pane fade" id="overview" role="tabpanel">
                            <h5 class="mb-4">
                                <i class="fas fa-chart-pie me-2"></i>Token System Overview
                                <button class="btn btn-sm btn-outline-primary float-end" onclick="refreshOverviewData()">
                                    <i class="fas fa-sync-alt me-1"></i>Refresh Data
                                </button>
                            </h5>
                            
                            <!-- All Budgets -->
                            <div class="row g-4 mb-4">
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-wallet me-2"></i>All Active Budgets
                                                <span class="badge bg-light text-dark ms-2"><?= count($all_budgets ?? []) ?> budgets</span>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body p-0">
                                            <div class="table-responsive">
                                                <table class="table table-hover mb-0">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Budget ID</th>
                                                            <th>Type</th>
                                                            <th>Owner</th>
                                                            <th>Balance</th>
                                                            <th>Total Spent</th>
                                                            <th>Created</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (isset($all_budgets) && count($all_budgets) > 0): ?>
                                                            <?php foreach ($all_budgets as $budget): ?>
                                                            <tr>
                                                                <td><span class="badge bg-secondary">#<?= $budget['id'] ?></span></td>
                                                                <td>
                                                                    <?php if ($budget['group_id']): ?>
                                                                        <span class="badge bg-info">
                                                                            <i class="fas fa-users me-1"></i>Group
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="badge bg-success">
                                                                            <i class="fas fa-user me-1"></i>Individual
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <?php if ($budget['group_name']): ?>
                                                                        <strong><?= htmlspecialchars($budget['group_name']) ?></strong>
                                                                        <br><small class="text-muted"><?= $budget['member_count'] ?> members</small>
                                                                    <?php else: ?>
                                                                        <a href="javascript:void(0)" onclick="viewUserBudget(<?= $budget['user_id'] ?>)" class="text-decoration-none">
                                                                            <?= htmlspecialchars($budget['owner_name'] ?? 'Unknown') ?>
                                                                        </a>
                                                                        <br><small class="text-muted">
                                                                            <a href="javascript:void(0)" onclick="viewUserTransactions(<?= $budget['user_id'] ?>)" class="text-decoration-none">
                                                                                @<?= htmlspecialchars($budget['owner_username'] ?? 'unknown') ?>
                                                                            </a>
                                                                        </small>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <a href="javascript:void(0)" onclick="viewBudgetTransactions(<?= $budget['id'] ?>)" class="text-decoration-none">
                                                                        <span class="badge bg-<?= $budget['balance'] > 50 ? 'success' : ($budget['balance'] > 10 ? 'warning' : 'danger') ?> fs-6">
                                                                            <?= number_format($budget['balance'], 2) ?>
                                                                        </span>
                                                                    </a>
                                                                </td>
                                                                <td><?= number_format($budget['total_spent'], 2) ?></td>
                                                                <td>
                                                                    <?= date('M j, Y', strtotime($budget['created_at'])) ?>
                                                                    <br><small class="text-muted">by <?= htmlspecialchars($budget['created_by_name'] ?? 'System') ?></small>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-<?= $budget['is_active'] ? 'success' : 'danger' ?>">
                                                                        <?= $budget['is_active'] ? 'Active' : 'Inactive' ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <button class="btn btn-sm btn-outline-primary" onclick="viewBudgetTransactions(<?= $budget['id'] ?>)">
                                                                        <i class="fas fa-history me-1"></i>Transactions
                                                                    </button>
                                                                    <?php if ($budget['group_id']): ?>
                                                                    <button class="btn btn-sm btn-outline-info" onclick="viewGroupMembers(<?= $budget['group_id'] ?>)">
                                                                        <i class="fas fa-users me-1"></i>Members
                                                                    </button>
                                                                    <?php endif; ?>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="8" class="text-center text-muted py-4">
                                                                    <i class="fas fa-info-circle me-2"></i>No budgets found
                                                                </td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- All Transactions -->
                            <div class="row g-4 mb-4">
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-success text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-exchange-alt me-2"></i>Recent Token Transactions
                                                <span class="badge bg-light text-dark ms-2">Last 100 transactions</span>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body p-0">
                                            <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                                                <table class="table table-hover mb-0">
                                                    <thead class="table-light sticky-top">
                                                        <tr>
                                                            <th>Transaction ID</th>
                                                            <th>Date</th>
                                                            <th>Type</th>
                                                            <th>Amount</th>
                                                            <th>Budget</th>
                                                            <th>Description</th>
                                                            <th>Balance After</th>
                                                            <th>Created By</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (isset($all_transactions) && count($all_transactions) > 0): ?>
                                                            <?php foreach ($all_transactions as $tx): ?>
                                                            <tr>
                                                                <td><span class="badge bg-secondary">#<?= $tx['id'] ?></span></td>
                                                                <td>
                                                                    <?= date('M j, H:i', strtotime($tx['created_at'])) ?>
                                                                    <br><small class="text-muted"><?= date('Y', strtotime($tx['created_at'])) ?></small>
                                                                </td>
                                                                <td>
                                                                    <?php
                                                                    $type_colors = [
                                                                        'credit' => 'success',
                                                                        'debit' => 'danger', 
                                                                        'purchase' => 'primary',
                                                                        'refund' => 'info',
                                                                        'adjustment' => 'warning'
                                                                    ];
                                                                    $type_icons = [
                                                                        'credit' => 'fas fa-plus',
                                                                        'debit' => 'fas fa-minus',
                                                                        'purchase' => 'fas fa-shopping-cart',
                                                                        'refund' => 'fas fa-undo',
                                                                        'adjustment' => 'fas fa-edit'
                                                                    ];
                                                                    $color = $type_colors[$tx['transaction_type']] ?? 'secondary';
                                                                    $icon = $type_icons[$tx['transaction_type']] ?? 'fas fa-circle';
                                                                    ?>
                                                                    <span class="badge bg-<?= $color ?>">
                                                                        <i class="<?= $icon ?> me-1"></i><?= ucfirst($tx['transaction_type']) ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <span class="text-<?= in_array($tx['transaction_type'], ['credit', 'purchase', 'refund']) ? 'success' : 'danger' ?>">
                                                                        <?= in_array($tx['transaction_type'], ['credit', 'purchase', 'refund']) ? '+' : '-' ?>
                                                                        <?= number_format($tx['amount'], 2) ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <a href="javascript:void(0)" onclick="viewBudgetTransactions(<?= $tx['budget_id'] ?>)" class="text-decoration-none">
                                                                        <span class="badge bg-light text-dark">#<?= $tx['budget_id'] ?></span>
                                                                    </a>
                                                                    <?php if ($tx['budget_owner'] && $tx['budget_owner_id']): ?>
                                                                        <br><small>
                                                                            <a href="javascript:void(0)" onclick="viewUserTransactions(<?= $tx['budget_owner_id'] ?>)" class="text-decoration-none text-muted">
                                                                                <?= htmlspecialchars($tx['budget_owner']) ?>
                                                                            </a>
                                                                        </small>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <?= htmlspecialchars($tx['description'] ?: 'No description') ?>
                                                                    <?php if ($tx['action_name']): ?>
                                                                        <br><small class="text-muted">Action: <?= htmlspecialchars($tx['action_name']) ?></small>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-<?= $tx['balance_after'] > 50 ? 'success' : ($tx['balance_after'] > 10 ? 'warning' : 'danger') ?>">
                                                                        <?= number_format($tx['balance_after'], 2) ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <?php if ($tx['created_by_id']): ?>
                                                                        <a href="javascript:void(0)" onclick="viewUserTransactions(<?= $tx['created_by_id'] ?>)" class="text-decoration-none">
                                                                            <?= htmlspecialchars($tx['created_by_name'] ?? 'System') ?>
                                                                        </a>
                                                                    <?php else: ?>
                                                                        <?= htmlspecialchars($tx['created_by_name'] ?? 'System') ?>
                                                                    <?php endif; ?>
                                                                    <?php if ($tx['created_by_role']): ?>
                                                                        <br><small class="text-muted"><?= ucfirst($tx['created_by_role']) ?></small>
                                                                    <?php endif; ?>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="8" class="text-center text-muted py-4">
                                                                    <i class="fas fa-info-circle me-2"></i>No transactions found
                                                                </td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Action Usage Statistics -->
                            <div class="row g-4 mb-4">
                                <div class="col-lg-6">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-warning text-dark">
                                            <h6 class="mb-0">
                                                <i class="fas fa-chart-bar me-2"></i>Token Action Usage
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <?php if (isset($action_usage) && count($action_usage) > 0): ?>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <thead>
                                                            <tr>
                                                                <th>Action</th>
                                                                <th>Usage Count</th>
                                                                <th>Total Tokens</th>
                                                                <th>Avg Cost</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($action_usage as $usage): ?>
                                                            <tr>
                                                                <td>
                                                                    <strong><?= htmlspecialchars($usage['action_name']) ?></strong>
                                                                    <br><small class="text-muted"><?= ucfirst($usage['category']) ?></small>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-primary"><?= $usage['usage_count'] ?></span>
                                                                </td>
                                                                <td>
                                                                    <span class="text-danger">-<?= number_format($usage['total_tokens'], 2) ?></span>
                                                                </td>
                                                                <td>
                                                                    <?= number_format($usage['avg_cost'], 2) ?>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            <?php else: ?>
                                                <div class="text-center text-muted py-3">
                                                    <i class="fas fa-info-circle me-2"></i>No action usage data available
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-lg-6">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-info text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-users me-2"></i>User Activity Summary
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <?php if (isset($user_activity) && count($user_activity) > 0): ?>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <thead>
                                                            <tr>
                                                                <th>User</th>
                                                                <th>Transactions</th>
                                                                <th>Total Spent</th>
                                                                <th>Balance</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($user_activity as $activity): ?>
                                                            <tr>
                                                                <td>
                                                                    <strong><?= htmlspecialchars($activity['full_name'] ?? $activity['username']) ?></strong>
                                                                    <br><small class="text-muted">@<?= htmlspecialchars($activity['username']) ?></small>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-secondary"><?= $activity['transaction_count'] ?></span>
                                                                </td>
                                                                <td>
                                                                    <span class="text-danger"><?= number_format($activity['total_spent'], 2) ?></span>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-<?= $activity['current_balance'] > 50 ? 'success' : ($activity['current_balance'] > 10 ? 'warning' : 'danger') ?>">
                                                                        <?= number_format($activity['current_balance'], 2) ?>
                                                                    </span>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            <?php else: ?>
                                                <div class="text-center text-muted py-3">
                                                    <i class="fas fa-info-circle me-2"></i>No user activity data available
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Export Options -->
                            <div class="row g-4">
                                <div class="col-12">
                                    <div class="border-0 shadow-none card border-primary">
                                        <div class="border-0 shadow-none card-header bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-download me-2"></i>Export & Reports
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-3">
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-primary w-100" onclick="exportAllTransactions()">
                                                        <i class="fas fa-file-csv me-2"></i>All Transactions CSV
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-success w-100" onclick="exportAllBudgets()">
                                                        <i class="fas fa-file-excel me-2"></i>All Budgets Excel
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-warning w-100" onclick="exportActionUsage()">
                                                        <i class="fas fa-chart-bar me-2"></i>Action Usage Report
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-info w-100" onclick="exportUserActivity()">
                                                        <i class="fas fa-users me-2"></i>User Activity Report
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Group Members Tab -->
                        <div class="tab-pane fade" id="groups" role="tabpanel">
                            <h5 class="mb-4">
                                <i class="fas fa-users me-2"></i>Group Members Management
                                <button class="btn btn-sm btn-outline-success float-end" data-bs-toggle="modal" data-bs-target="#addGroupModal">
                                    <i class="fas fa-plus me-1"></i>Create Group
                                </button>
                            </h5>
                            
                            <!-- Groups Overview -->
                            <div class="row g-4 mb-4">
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-info text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-layer-group me-2"></i>All Groups Overview
                                                <span class="badge bg-light text-dark ms-2"><?= count($all_groups ?? []) ?> groups</span>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body p-0">
                                            <div class="table-responsive">
                                                <table class="table table-hover mb-0">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Group</th>
                                                            <th>Members</th>
                                                            <th>Budget</th>
                                                            <th>Created</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (isset($all_groups) && count($all_groups) > 0): ?>
                                                            <?php foreach ($all_groups as $group): ?>
                                                            <tr>
                                                                <td>
                                                                    <div class="d-flex align-items-center">
                                                                        <div class="color-box me-2" style="width: 16px; height: 16px; background-color: <?= htmlspecialchars($group['color']) ?>; border-radius: 3px;"></div>
                                                                        <div>
                                                                            <strong><?= htmlspecialchars($group['name']) ?></strong>
                                                                            <?php if ($group['description']): ?>
                                                                                <br><small class="text-muted"><?= htmlspecialchars($group['description']) ?></small>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-primary"><?= $group['member_count'] ?> members</span>
                                                                    <?php if ($group['member_count'] > 0): ?>
                                                                        <br><small class="text-muted" title="<?= htmlspecialchars($group['members_list'] ?? '') ?>">
                                                                            <?= strlen($group['members_list'] ?? '') > 50 ? substr($group['members_list'], 0, 47) . '...' : $group['members_list'] ?>
                                                                        </small>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <?php if ($group['budget_id']): ?>
                                                                        <span class="badge bg-<?= $group['group_budget'] > 50 ? 'success' : ($group['group_budget'] > 10 ? 'warning' : 'danger') ?> fs-6">
                                                                            <?= number_format($group['group_budget'], 2) ?> tokens
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="text-muted">No budget</span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <?= date('M j, Y', strtotime($group['created_at'])) ?>
                                                                    <?php if ($group['created_by_name']): ?>
                                                                        <br><small class="text-muted">by <?= htmlspecialchars($group['created_by_name']) ?></small>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-<?= $group['is_active'] ? 'success' : 'danger' ?>">
                                                                        <?= $group['is_active'] ? 'Active' : 'Inactive' ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <div class="btn-group btn-group-sm">
                                                                        <button class="btn btn-outline-primary" onclick="viewGroupDetails(<?= $group['id'] ?>)" title="View Details">
                                                                            <i class="fas fa-eye"></i>
                                                                        </button>
                                                                        <button class="btn btn-outline-info" onclick="manageGroupMembers(<?= $group['id'] ?>)" title="Manage Members">
                                                                            <i class="fas fa-users-cog"></i>
                                                                        </button>
                                                                        <?php if (!$group['budget_id']): ?>
                                                                        <button class="btn btn-outline-success" onclick="createGroupBudget(<?= $group['id'] ?>)" title="Create Budget">
                                                                            <i class="fas fa-wallet"></i>
                                                                        </button>
                                                                        <?php endif; ?>
                                                                        <button class="btn btn-outline-warning" onclick="editGroup(<?= $group['id'] ?>)" title="Edit Group">
                                                                            <i class="fas fa-edit"></i>
                                                                        </button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="6" class="text-center text-muted py-4">
                                                                    <i class="fas fa-info-circle me-2"></i>No groups found
                                                                </td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Detailed Group Memberships -->
                            <div class="row g-4">
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-address-book me-2"></i>Detailed Group Memberships
                                                <button class="btn btn-sm btn-outline-light float-end" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                                                    <i class="fas fa-user-plus me-1"></i>Add Member
                                                </button>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body p-0">
                                            <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                                                <table class="table table-hover mb-0">
                                                    <thead class="table-light sticky-top">
                                                        <tr>
                                                            <th>Group</th>
                                                            <th>Member</th>
                                                            <th>Role</th>
                                                            <th>Joined</th>
                                                            <th>Added By</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (isset($group_memberships) && count($group_memberships) > 0): ?>
                                                            <?php 
                                                            $current_group = null;
                                                            foreach ($group_memberships as $membership): 
                                                            ?>
                                                            <tr <?= $current_group !== $membership['group_id'] ? 'class="border-top-2"' : '' ?>>
                                                                <td>
                                                                    <?php if ($current_group !== $membership['group_id']): ?>
                                                                        <div class="d-flex align-items-center">
                                                                            <div class="color-box me-2" style="width: 12px; height: 12px; background-color: <?= htmlspecialchars($membership['group_color']) ?>; border-radius: 2px;"></div>
                                                                            <strong><?= htmlspecialchars($membership['group_name']) ?></strong>
                                                                        </div>
                                                                        <?php $current_group = $membership['group_id']; ?>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <div>
                                                                        <h6 class="mb-0"><?= htmlspecialchars($membership['full_name'] ?: $membership['username']) ?></h6>
                                                                        <small class="text-muted">@<?= htmlspecialchars($membership['username']) ?></small>
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <?php
                                                                    $role_colors = [
                                                                        'owner' => 'danger',
                                                                        'manager' => 'warning', 
                                                                        'member' => 'info'
                                                                    ];
                                                                    $role_color = $role_colors[$membership['role_in_group']] ?? 'secondary';
                                                                    ?>
                                                                    <span class="badge bg-<?= $role_color ?>">
                                                                        <?= ucfirst($membership['role_in_group']) ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <?= date('M j, Y', strtotime($membership['joined_at'])) ?>
                                                                    <br><small class="text-muted"><?= date('H:i', strtotime($membership['joined_at'])) ?></small>
                                                                </td>
                                                                <td>
                                                                    <small><?= htmlspecialchars($membership['added_by_name'] ?: 'System') ?></small>
                                                                </td>
                                                                <td>
                                                                    <div class="btn-group btn-group-sm">
                                                                        <button class="btn btn-outline-warning" onclick="changeUserRole(<?= $membership['group_id'] ?>, <?= $membership['user_id'] ?>)" title="Change Role">
                                                                            <i class="fas fa-user-edit"></i>
                                                                        </button>
                                                                        <button class="btn btn-outline-danger" onclick="removeFromGroup(<?= $membership['group_id'] ?>, <?= $membership['user_id'] ?>)" title="Remove from Group">
                                                                            <i class="fas fa-user-minus"></i>
                                                                        </button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="6" class="text-center text-muted py-4">
                                                                    <i class="fas fa-info-circle me-2"></i>No group memberships found
                                                                </td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Help & Documentation Tab -->
                        <div class="tab-pane fade" id="help" role="tabpanel">
                            <h5 class="mb-4">Token System Documentation & Help</h5>
                            
                            <div class="row g-4">
                                <!-- Database Schema -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-database me-2"></i>📊 Comprehensive Database Schema
                                                <small class="ms-2">(setup_token_system.sql)</small>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-primary">budgets table</h6>
                                                        <p class="small text-muted mb-0">Linked to user groups for centralized budget management</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-primary">token_actions table</h6>
                                                        <p class="small text-muted mb-0">Configurable pricing (add_participant: 1 token, create_event: 30 tokens, etc.)</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-primary">token_transactions table</h6>
                                                        <p class="small text-muted mb-0">Complete audit trail for all token movements</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-primary">token_packages table</h6>
                                                        <p class="small text-muted mb-0">Purchasing options with bonus tokens</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- TokenSystem PHP Class -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-success text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-cogs me-2"></i>🔧 TokenSystem PHP Class
                                                <small class="ms-2">(includes/TokenSystem.php)</small>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-success">charge() method</h6>
                                                        <p class="small text-muted mb-0">For deducting tokens with transaction logging</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-success">canAfford() method</h6>
                                                        <p class="small text-muted mb-0">Pre-checking balances before operations</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-success">addTokens() method</h6>
                                                        <p class="small text-muted mb-0">For crediting accounts with purchase/admin adjustments</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-success">getBalance() method</h6>
                                                        <p class="small text-muted mb-0">Real-time balance checking</p>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="feature-item p-3 border rounded bg-light">
                                                        <h6 class="text-success">Additional Features</h6>
                                                        <p class="small text-muted mb-0">Transaction logging, refund capabilities, usage tracking, and comprehensive error handling</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Admin Management Panel -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-warning text-dark">
                                            <h6 class="mb-0">
                                                <i class="fas fa-tools me-2"></i>🎛️ Admin Management Panel
                                                <small class="ms-2">(admin/token_management.php)</small>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-warning">Token Actions Tab</h6>
                                                        <p class="small text-muted mb-0">Configure pricing for any platform feature</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-warning">Token Packages Tab</h6>
                                                        <p class="small text-muted mb-0">Create purchase packages with bonuses</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-warning">Budget Management Tab</h6>
                                                        <p class="small text-muted mb-0">Add tokens to users, view balances</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-warning">Code Generator Tab</h6>
                                                        <p class="small text-muted mb-0">Get integration snippets for any action</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Integration Examples -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card">
                                        <div class="border-0 shadow-none card-header bg-info text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-book me-2"></i>📚 Integration Examples
                                                <small class="ms-2">(includes/token_examples.php)</small>
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-info">Ready-to-use code snippets</h6>
                                                        <p class="small text-muted mb-0">For charging tokens in your existing code</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-info">AJAX integration examples</h6>
                                                        <p class="small text-muted mb-0">For real-time token charging in web interfaces</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-info">Error handling mechanisms</h6>
                                                        <p class="small text-muted mb-0">Refund capabilities for failed operations</p>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="feature-item p-3 border rounded">
                                                        <h6 class="text-info">UI component examples</h6>
                                                        <p class="small text-muted mb-0">Widgets, forms, and user interfaces</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Quick Start Guide -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card border-success">
                                        <div class="border-0 shadow-none card-header bg-success text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-rocket me-2"></i>🚀 Quick Start Guide
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <ol class="mb-0">
                                                <li class="mb-2"><strong>Setup Database:</strong> Run <code>mysql -u username -p database < includes/setup_token_system.sql</code></li>
                                                <li class="mb-2"><strong>Include TokenSystem:</strong> Add <code>require_once 'includes/TokenSystem.php';</code> to your files</li>
                                                <li class="mb-2"><strong>Basic Usage:</strong> Use <code>TokenSystem::charge('action_name', $user_id);</code> to charge tokens</li>
                                                <li class="mb-2"><strong>Check Balance:</strong> Use <code>TokenSystem::canAfford('action_name', $user_id);</code> before operations</li>
                                                <li class="mb-0"><strong>Configure Actions:</strong> Use this admin panel to add custom token actions and pricing</li>
                                            </ol>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- File Locations -->
                                <div class="col-12">
                                    <div class="border-0 shadow-none card border-dark">
                                        <div class="border-0 shadow-none card-header bg-dark text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-folder me-2"></i>📁 File Locations
                                            </h6>
                                        </div>
                                        <div class="border-0 shadow-none card-body">
                                            <div class="row g-2">
                                                <div class="col-md-6">
                                                    <code>/includes/setup_token_system.sql</code> - Database schema
                                                </div>
                                                <div class="col-md-6">
                                                    <code>/includes/TokenSystem.php</code> - Core PHP class
                                                </div>
                                                <div class="col-md-6">
                                                    <code>/admin/token_management.php</code> - This admin panel
                                                </div>
                                                <div class="col-md-6">
                                                    <code>/includes/token_examples.php</code> - Integration examples
                                                </div>
                                                <div class="col-md-6">
                                                    <code>/TOKEN_SETUP_GUIDE.md</code> - Complete documentation
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Action Modal -->
    <div class="modal fade" id="addActionModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-plus me-2"></i>Add New Token Action
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <input type="hidden" name="action" value="add_action">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Action Name *</label>
                                <input type="text" class="form-control" name="action_name" required placeholder="e.g., add_participant">
                                <div class="form-text">Use lowercase with underscores</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Token Cost *</label>
                                <input type="number" class="form-control" name="token_cost" step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Category *</label>
                                <select class="form-select" name="category" required>
                                    <option value="general">General</option>
                                    <option value="participants">Participants</option>
                                    <option value="judges">Judges</option>
                                    <option value="events">Events</option>
                                    <option value="reports">Reports</option>
                                    <option value="communications">Communications</option>
                                    <option value="premium">Premium</option>
                                    <option value="integrations">Integrations</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Reference Type</label>
                                <input type="text" class="form-control" name="reference_type" placeholder="e.g., event_id">
                                <div class="form-text">For code generation</div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Description *</label>
                                <textarea class="form-control" name="action_description" rows="3" required></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Add Action
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Package Modal -->
    <div class="modal fade" id="addPackageModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-box me-2"></i>Create Token Package
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <input type="hidden" name="action" value="create_package">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Package Name *</label>
                            <input type="text" class="form-control" name="package_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="package_description" rows="3"></textarea>
                        </div>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Token Amount *</label>
                                <input type="number" class="form-control" name="token_amount" step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Price *</label>
                                <input type="number" class="form-control" name="price" step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Bonus Tokens</label>
                                <input type="number" class="form-control" name="bonus_tokens" step="0.01" value="0">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Sort Order</label>
                                <input type="number" class="form-control" name="sort_order" value="0">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Create Package
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Tokens Modal -->
    <div class="modal fade" id="addTokensModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-plus me-2"></i>Add Tokens to User
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <input type="hidden" name="action" value="add_tokens">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Select User *</label>
                            <select class="form-select" name="target_user_id" required>
                                <option value="">Choose user...</option>
                                <?php foreach ($users as $user): ?>
                                <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?> (<?= $user['balance'] ?: 0 ?> tokens)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount *</label>
                            <input type="number" class="form-control" name="amount" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" rows="2" placeholder="Admin credit adjustment"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-plus me-2"></i>Add Tokens
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- User Budget Modal -->
    <div class="modal fade" id="userBudgetModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-wallet me-2"></i>User Budget Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="budgetContent">
                        <div class="text-center">
                            <div class="spinner-border" role="status"></div>
                            <p class="mt-2">Loading budget details...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success" onclick="addTokensToCurrentUser()">
                        <i class="fas fa-plus me-2"></i>Add Tokens
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction History Modal -->
    <div class="modal fade" id="transactionModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-history me-2"></i>Transaction History
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="transactionContent">
                        <div class="text-center">
                            <div class="spinner-border" role="status"></div>
                            <p class="mt-2">Loading transactions...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="exportTransactions()">
                        <i class="fas fa-download me-2"></i>Export CSV
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Group Modal -->
    <div class="modal fade" id="addGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-users me-2"></i>Create New Group
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create_group">
                        <div class="mb-3">
                            <label class="form-label">Group Name</label>
                            <input type="text" class="form-control" name="group_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="group_description" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Color</label>
                            <input type="color" class="form-control form-control-color" name="group_color" value="#007bff">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Initial Budget (optional)</label>
                            <input type="number" class="form-control" name="initial_budget" step="0.01" min="0" placeholder="0.00">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-plus me-2"></i>Create Group
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Member Modal -->
    <div class="modal fade" id="addMemberModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user-plus me-2"></i>Add Member to Group
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_member">
                        <div class="mb-3">
                            <label class="form-label">Select Group</label>
                            <select class="form-select" name="group_id" required>
                                <option value="">Choose group...</option>
                                <?php foreach ($all_groups as $group): ?>
                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Select User</label>
                            <select class="form-select" name="user_id" required>
                                <option value="">Choose user...</option>
                                <?php foreach ($users as $user): ?>
                                <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?> (@<?= htmlspecialchars($user['username']) ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Role in Group</label>
                            <select class="form-select" name="role_in_group" required>
                                <option value="member">Member</option>
                                <option value="manager">Manager</option>
                                <option value="owner">Owner</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-user-plus me-2"></i>Add Member
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Group Details Modal -->
    <div class="modal fade" id="groupDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Group Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="groupDetailsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading group details...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Group Members Modal -->
    <div class="modal fade" id="groupMembersModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Group Members</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="groupMembersContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading group members...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Manage Group Members Modal -->
    <div class="modal fade" id="manageGroupMembersModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Manage Group Members</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="manageGroupMembersContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading member management...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Budget Transactions Modal -->
    <div class="modal fade" id="budgetTransactionsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Budget Transactions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="budgetTransactionsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading transactions...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- User Transactions Modal -->
    <div class="modal fade" id="userTransactionsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">User Transactions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userTransactionsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading user transactions...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- User Budget Modal -->
    <div class="modal fade" id="userBudgetModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">User Budget</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userBudgetContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading user budget...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Budget Modal -->
    <div class="modal fade" id="createBudgetModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Group Budget</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="createBudgetForm">
                    <div class="modal-body">
                        <input type="hidden" id="budgetGroupId" name="group_id">
                        <div class="mb-3">
                            <label for="budgetAmount" class="form-label">Initial Budget Amount</label>
                            <input type="number" class="form-control" id="budgetAmount" name="amount" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="budgetCurrency" class="form-label">Currency</label>
                            <select class="form-select" id="budgetCurrency" name="currency">
                                <option value="USD">USD</option>
                                <option value="EUR">EUR</option>
                                <option value="GBP">GBP</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="budgetActive" name="is_active" checked>
                                <label class="form-check-label" for="budgetActive">
                                    Active Budget
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Create Budget</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Action Modal -->
    <div class="modal fade" id="addActionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Token Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_action">
                        <div class="mb-3">
                            <label for="action_name" class="form-label">Action Name</label>
                            <input type="text" class="form-control" id="action_name" name="action_name" required>
                        </div>
                        <div class="mb-3">
                            <label for="action_description" class="form-label">Description</label>
                            <textarea class="form-control" id="action_description" name="action_description" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="token_cost" class="form-label">Token Cost</label>
                            <input type="number" class="form-control" id="token_cost" name="token_cost" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="category" class="form-label">Category</label>
                            <select class="form-select" id="category" name="category" required>
                                <option value="participants">Participants</option>
                                <option value="events">Events</option>
                                <option value="judges">Judges</option>
                                <option value="reports">Reports</option>
                                <option value="communications">Communications</option>
                                <option value="premium">Premium</option>
                                <option value="scoring">Scoring</option>
                                <option value="general">General</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="reference_type" class="form-label">Reference Type</label>
                            <input type="text" class="form-control" id="reference_type" name="reference_type" placeholder="e.g., event_id, participant_id" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Action</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Action Modal -->
    <div class="modal fade" id="editActionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Token Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="editActionForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_action">
                        <input type="hidden" id="edit_action_id" name="action_id">
                        <div class="mb-3">
                            <label for="edit_action_description" class="form-label">Description</label>
                            <textarea class="form-control" id="edit_action_description" name="action_description" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="edit_token_cost" class="form-label">Token Cost</label>
                            <input type="number" class="form-control" id="edit_token_cost" name="token_cost" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit_category" class="form-label">Category</label>
                            <select class="form-select" id="edit_category" name="category" required>
                                <option value="participants">Participants</option>
                                <option value="events">Events</option>
                                <option value="judges">Judges</option>
                                <option value="reports">Reports</option>
                                <option value="communications">Communications</option>
                                <option value="premium">Premium</option>
                                <option value="scoring">Scoring</option>
                                <option value="general">General</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active">
                                <label class="form-check-label" for="edit_is_active">
                                    Active
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Code Modal -->
    <div class="modal fade" id="viewCodeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Code for Action</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="codeContent">
                        <div class="text-center py-4">
                            <div class="spinner-border" role="status"></div>
                            <p class="mt-2">Loading code...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="copyCode()">Copy Code</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Package Modal -->
    <div class="modal fade" id="addPackageModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Token Package</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create_package">
                        <div class="mb-3">
                            <label for="package_name" class="form-label">Package Name</label>
                            <input type="text" class="form-control" id="package_name" name="package_name" required>
                        </div>
                        <div class="mb-3">
                            <label for="package_description" class="form-label">Description</label>
                            <textarea class="form-control" id="package_description" name="package_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="token_amount" class="form-label">Token Amount</label>
                            <input type="number" class="form-control" id="token_amount" name="token_amount" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label for="price" class="form-label">Price ($)</label>
                            <input type="number" class="form-control" id="price" name="price" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="bonus_tokens" class="form-label">Bonus Tokens</label>
                            <input type="number" class="form-control" id="bonus_tokens" name="bonus_tokens" min="0" value="0">
                        </div>
                        <div class="mb-3">
                            <label for="sort_order" class="form-label">Sort Order</label>
                            <input type="number" class="form-control" id="sort_order" name="sort_order" min="0" value="0">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create Package</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Package Modal -->
    <div class="modal fade" id="editPackageModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Token Package</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="editPackageContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading package details...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Tokens Modal -->
    <div class="modal fade" id="addTokensModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Tokens to User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_tokens">
                        <div class="mb-3">
                            <label for="target_user_id" class="form-label">Select User</label>
                            <select class="form-select" id="target_user_id" name="target_user_id" required>
                                <option value="">Choose a user...</option>
                                <?php foreach ($users as $user): ?>
                                <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?> (@<?= htmlspecialchars($user['username']) ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="amount" class="form-label">Amount</label>
                            <input type="number" class="form-control" id="amount" name="amount" min="0.01" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <input type="text" class="form-control" id="description" name="description" placeholder="Reason for adding tokens">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Add Tokens</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Group Modal -->
    <div class="modal fade" id="addGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create New Group</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create_group">
                        <div class="mb-3">
                            <label for="group_name" class="form-label">Group Name</label>
                            <input type="text" class="form-control" id="group_name" name="group_name" required>
                        </div>
                        <div class="mb-3">
                            <label for="group_description" class="form-label">Description</label>
                            <textarea class="form-control" id="group_description" name="group_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="group_color" class="form-label">Group Color</label>
                            <input type="color" class="form-control form-control-color" id="group_color" name="group_color" value="#6f42c1">
                        </div>
                        <div class="mb-3">
                            <label for="initial_budget" class="form-label">Initial Budget (optional)</label>
                            <input type="number" class="form-control" id="initial_budget" name="initial_budget" min="0" step="0.01">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Create Group</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Group Details Modal -->
    <div class="modal fade" id="groupDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Group Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="groupDetailsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading group details...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Group Members Modal -->
    <div class="modal fade" id="groupMembersModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Group Members</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="groupMembersContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading group members...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Manage Group Members Modal -->
    <div class="modal fade" id="manageGroupMembersModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Manage Group Members</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="manageGroupMembersContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading member management...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Budget Transactions Modal -->
    <div class="modal fade" id="budgetTransactionsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Budget Transactions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="budgetTransactionsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading transactions...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- User Transactions Modal -->
    <div class="modal fade" id="userTransactionsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">User Transactions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userTransactionsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading user transactions...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- User Budget Modal -->
    <div class="modal fade" id="userBudgetModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">User Budget</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userBudgetContent">
                    <div class="text-center py-4">
                        <div class="spinner-border" role="status"></div>
                        <p class="mt-2">Loading user budget...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Budget Modal -->
    <div class="modal fade" id="createBudgetModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Group Budget</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="createBudgetForm">
                    <div class="modal-body">
                        <input type="hidden" id="budgetGroupId" name="group_id">
                        <div class="mb-3">
                            <label for="budgetAmount" class="form-label">Initial Budget Amount</label>
                            <input type="number" class="form-control" id="budgetAmount" name="amount" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="budgetCurrency" class="form-label">Currency</label>
                            <select class="form-select" id="budgetCurrency" name="currency">
                                <option value="USD">USD</option>
                                <option value="EUR">EUR</option>
                                <option value="GBP">GBP</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="budgetActive" name="is_active" checked>
                                <label class="form-check-label" for="budgetActive">
                                    Active Budget
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Create Budget</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentUserId = null;

        function editAction(actionId) {
            // TODO: Implement edit action
            console.log('Edit action:', actionId);
        }
        
        function deleteAction(actionId) {
            if (confirm('Are you sure you want to delete this action?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_action">
                    <input type="hidden" name="action_id" value="${actionId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function viewCode(actionName) {
            const code = `TokenSystem::charge('${actionName}', $user_id, ['reference_id' => $id]);`;
            navigator.clipboard.writeText(code).then(() => {
                alert('Code snippet copied to clipboard!');
            });
        }
        
        function editPackage(packageId) {
            console.log('Edit package:', packageId);
        }
        
        function deletePackage(packageId) {
            if (confirm('Are you sure you want to delete this package?')) {
                // TODO: Implement delete package
                console.log('Delete package:', packageId);
            }
        }
        
        function addTokensToUser(userId) {
            currentUserId = userId;
            document.querySelector('select[name="target_user_id"]').value = userId;
            const modal = new bootstrap.Modal(document.getElementById('addTokensModal'));
            modal.show();
        }

        function addTokensToCurrentUser() {
            if (currentUserId) {
                addTokensToUser(currentUserId);
                // Close budget modal
                const budgetModal = bootstrap.Modal.getInstance(document.getElementById('userBudgetModal'));
                if (budgetModal) budgetModal.hide();
            }
        }
        
        function viewTransactions(userId) {
            currentUserId = userId;
            const modal = new bootstrap.Modal(document.getElementById('transactionModal'));
            modal.show();

            // Fetch transaction data
            fetch(`api/token_management_api.php?action=get_transactions&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayTransactions(data.transactions, data.user_info);
                    } else {
                        document.getElementById('transactionContent').innerHTML = `
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                ${data.message || 'Unable to load transactions'}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('transactionContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading transactions: ${error.message}
                        </div>
                    `;
                });
        }
        
        function viewUserBudget(userId) {
            currentUserId = userId;
            const modal = new bootstrap.Modal(document.getElementById('userBudgetModal'));
            modal.show();

            // Fetch budget data
            fetch(`api/token_management_api.php?action=get_user_budget&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBudgetDetails(data.budget, data.user_info, data.group_info);
                    } else {
                        document.getElementById('budgetContent').innerHTML = `
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                ${data.message || 'Unable to load budget details'}
                                <button class="btn btn-primary btn-sm ms-3" onclick="createBudgetForUser(${userId})">
                                    <i class="fas fa-plus me-1"></i>Create Budget
                                </button>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('budgetContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading budget: ${error.message}
                        </div>
                    `;
                });
        }

        function displayTransactions(transactions, userInfo) {
            let html = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h6 class="mb-0">${userInfo.full_name || userInfo.username}</h6>
                        <small class="text-muted">@${userInfo.username}</small>
                    </div>
                    <div class="badge bg-primary fs-6">
                        Current Balance: ${parseFloat(userInfo.balance || 0).toFixed(2)} tokens
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Description</th>
                                <th>Reference</th>
                                <th>Balance After</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (transactions.length === 0) {
                html += `
                    <tr>
                        <td colspan="6" class="text-center text-muted py-4">
                            <i class="fas fa-info-circle me-2"></i>No transactions found
                        </td>
                    </tr>
                `;
            } else {
                transactions.forEach(tx => {
                    const isCredit = ['credit', 'purchase', 'refund'].includes(tx.transaction_type);
                    const amountClass = isCredit ? 'text-success' : 'text-danger';
                    const amountSign = isCredit ? '+' : '-';
                    
                    html += `
                        <tr>
                            <td>${new Date(tx.created_at).toLocaleDateString()}</td>
                            <td>
                                <span class="badge bg-${isCredit ? 'success' : 'warning'}">
                                    ${tx.transaction_type}
                                </span>
                            </td>
                            <td class="${amountClass}">
                                <strong>${amountSign}${parseFloat(tx.amount).toFixed(2)}</strong>
                            </td>
                            <td>${tx.description || '-'}</td>
                            <td>
                                ${tx.reference_type ? `<small>${tx.reference_type}: ${tx.reference_id}</small>` : '-'}
                            </td>
                            <td>${parseFloat(tx.balance_after || 0).toFixed(2)}</td>
                        </tr>
                    `;
                });
            }

            html += `
                        </tbody>
                    </table>
                </div>
            `;

            document.getElementById('transactionContent').innerHTML = html;
        }

        function displayBudgetDetails(budget, userInfo, groupInfo) {
            let html = `
                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="border-0 shadow-none card">
                            <div class="border-0 shadow-none card-header">
                                <h6 class="mb-0">
                                    <i class="fas fa-user me-2"></i>User Information
                                </h6>
                            </div>
                            <div class="border-0 shadow-none card-body">
                                <p><strong>Name:</strong> ${userInfo.full_name || userInfo.username}</p>
                                <p><strong>Username:</strong> @${userInfo.username}</p>
                                <p><strong>Role:</strong> <span class="badge bg-secondary">${userInfo.role}</span></p>
                                <p class="mb-0"><strong>Status:</strong> 
                                    <span class="badge bg-${userInfo.is_active ? 'success' : 'danger'}">
                                        ${userInfo.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="border-0 shadow-none card">
                            <div class="border-0 shadow-none card-header">
                                <h6 class="mb-0">
                                    <i class="fas fa-wallet me-2"></i>Budget Information
                                </h6>
                            </div>
                            <div class="border-0 shadow-none card-body">
            `;

            if (budget) {
                html += `
                    <p><strong>Current Balance:</strong> 
                        <span class="badge bg-${budget.balance > 50 ? 'success' : budget.balance > 10 ? 'warning' : 'danger'} fs-6">
                            ${parseFloat(budget.balance).toFixed(2)} tokens
                        </span>
                    </p>
                    <p><strong>Total Spent:</strong> ${parseFloat(budget.total_spent || 0).toFixed(2)} tokens</p>
                    <p><strong>Budget Status:</strong> 
                        <span class="badge bg-${budget.is_active ? 'success' : 'danger'}">
                            ${budget.is_active ? 'Active' : 'Inactive'}
                        </span>
                    </p>
                    ${groupInfo ? `
                        <p><strong>Group:</strong> 
                            <span class="badge" style="background-color: ${groupInfo.color || '#6c757d'}">
                                ${groupInfo.name}
                            </span>
                        </p>
                    ` : ''}
                    <p class="mb-0"><strong>Last Updated:</strong> ${new Date(budget.updated_at).toLocaleDateString()}</p>
                `;
            } else {
                html += `
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        No budget found for this user. A budget will be created automatically when tokens are added.
                    </div>
                `;
            }

            html += `
                            </div>
                        </div>
                    </div>
                </div>
            `;

            document.getElementById('budgetContent').innerHTML = html;
        }

        function createBudgetForUser(userId) {
            if (confirm('Create a new budget for this user?')) {
                fetch('api/token_management_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=create_budget&user_id=${userId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Budget created successfully!');
                        viewUserBudget(userId); // Refresh the modal
                    } else {
                        alert('Error creating budget: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Network error: ' + error.message);
                });
            }
        }

        function exportTransactions() {
            if (currentUserId) {
                window.open(`api/token_management_api.php?action=export_transactions&user_id=${currentUserId}`, '_blank');
            }
        }
        
        
        // System Overview functions
        function refreshOverviewData() {
            location.reload();
        }
        
        function viewBudgetTransactions(budgetId) {
            const modal = new bootstrap.Modal(document.getElementById('transactionModal'));
            modal.show();
            
            // Fetch transaction data for specific budget
            fetch(`api/token_management_api.php?action=get_budget_transactions&budget_id=${budgetId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBudgetTransactions(data.transactions, data.budget_info);
                    } else {
                        document.getElementById('transactionContent').innerHTML = `
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                No transactions found for this budget: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('transactionContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading budget transactions: ${error.message}
                        </div>
                    `;
                });
        }
        
        function viewGroupMembers(groupId) {
            alert(`Group members feature will be implemented. Group ID: ${groupId}`);
            // TODO: Implement group members modal
        }
        
        function displayBudgetTransactions(transactions, budgetInfo) {
            let html = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h6 class="mb-0">Budget #${budgetInfo.id} Transactions</h6>
                        <small class="text-muted">${budgetInfo.type} Budget - ${budgetInfo.owner}</small>
                    </div>
                    <div class="badge bg-primary fs-6">
                        Current Balance: ${parseFloat(budgetInfo.balance || 0).toFixed(2)} tokens
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Description</th>
                                <th>Action</th>
                                <th>Balance After</th>
                                <th>Created By</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            if (transactions.length === 0) {
                html += `
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            <i class="fas fa-info-circle me-2"></i>No transactions found for this budget
                        </td>
                    </tr>
                `;
            } else {
                transactions.forEach(tx => {
                    const isCredit = ['credit', 'purchase', 'refund'].includes(tx.transaction_type);
                    const amountClass = isCredit ? 'text-success' : 'text-danger';
                    const amountSign = isCredit ? '+' : '-';
                    
                    html += `
                        <tr>
                            <td>${new Date(tx.created_at).toLocaleDateString()}</td>
                            <td>
                                <span class="badge bg-${getTransactionTypeColor(tx.transaction_type)}">
                                    ${tx.transaction_type.charAt(0).toUpperCase() + tx.transaction_type.slice(1)}
                                </span>
                            </td>
                            <td class="${amountClass}">
                                ${amountSign}${parseFloat(tx.amount).toFixed(2)}
                            </td>
                            <td>${tx.description || '-'}</td>
                            <td>${tx.action_name || '-'}</td>
                            <td>${parseFloat(tx.balance_after || 0).toFixed(2)}</td>
                            <td>${tx.created_by_name || 'System'}</td>
                        </tr>
                    `;
                });
            }

            html += `
                        </tbody>
                    </table>
                </div>
            `;

            document.getElementById('transactionContent').innerHTML = html;
        }
        
        function getTransactionTypeColor(type) {
            const colors = {
                'credit': 'success',
                'debit': 'danger', 
                'purchase': 'primary',
                'refund': 'info',
                'adjustment': 'warning'
            };
            return colors[type] || 'secondary';
        }
        
        // Export functions
        function exportAllTransactions() {
            window.open('api/token_management_api.php?action=export_all_transactions', '_blank');
        }
        
        function exportAllBudgets() {
            window.open('api/token_management_api.php?action=export_all_budgets', '_blank');
        }
        
        function exportActionUsage() {
            window.open('api/token_management_api.php?action=export_action_usage', '_blank');
        }
        
        function exportUserActivity() {
            window.open('api/token_management_api.php?action=export_user_activity', '_blank');
        }
        
        // Group management functions
        function viewGroupDetails(groupId) {
            // Implementation for viewing group details
            alert('View group details: ' + groupId);
        }
        
        function manageGroupMembers(groupId) {
            // Implementation for managing group members
            alert('Manage members for group: ' + groupId);
        }
        
        function createGroupBudget(groupId) {
            // Implementation for creating group budget
            if (confirm('Create a budget for this group?')) {
                // You can implement AJAX call here
                alert('Creating budget for group: ' + groupId);
            }
        }
        
        function editGroup(groupId) {
            // Implementation for editing group
            alert('Edit group: ' + groupId);
        }
        
        function changeUserRole(groupId, userId) {
            // Implementation for changing user role
            alert('Change role for user ' + userId + ' in group ' + groupId);
        }
        
        function removeFromGroup(groupId, userId) {
            if (confirm('Are you sure you want to remove this user from the group?')) {
                // Implementation for removing user from group
                alert('Remove user ' + userId + ' from group ' + groupId);
            }
        }
        
        // Other management functions
        function editAction(actionId) {
            alert('Edit action: ' + actionId);
        }
        
        function viewCode(actionName) {
            alert('View code for: ' + actionName);
        }
        
        function deleteAction(actionId) {
            if (confirm('Are you sure you want to delete this action?')) {
                alert('Delete action: ' + actionId);
            }
        }
        
        function editPackage(packageId) {
            alert('Edit package: ' + packageId);
        }
        
        function deletePackage(packageId) {
            if (confirm('Are you sure you want to delete this package?')) {
                alert('Delete package: ' + packageId);
            }
        }
        
        function viewTransactions(userId) {
            alert('View transactions for user: ' + userId);
        }
        
        function addTokensToUser(userId) {
            // Pre-select the user in the modal
            const modal = new bootstrap.Modal(document.getElementById('addTokensModal'));
            const userSelect = document.querySelector('#addTokensModal select[name="target_user_id"]');
            if (userSelect) {
                userSelect.value = userId;
            }
            modal.show();
        }
        
        // Enhanced functionality for viewing and managing data
        
        function viewGroupDetails(groupId) {
            fetch(`token_management_api.php?action=get_group_details&group_id=${groupId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('groupDetailsContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('groupDetailsModal')).show();
                    } else {
                        alert('Error loading group details: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading group details');
                });
        }
        
        function viewGroupMembers(groupId) {
            fetch(`token_management_api.php?action=get_group_members&group_id=${groupId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('groupMembersContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('groupMembersModal')).show();
                    } else {
                        alert('Error loading group members: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading group members');
                });
        }
        
        function manageGroupMembers(groupId) {
            fetch(`token_management_api.php?action=manage_group_members&group_id=${groupId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('manageGroupMembersContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('manageGroupMembersModal')).show();
                    } else {
                        alert('Error loading member management: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading member management');
                });
        }
        
        function createGroupBudget(groupId) {
            document.getElementById('budgetGroupId').value = groupId;
            new bootstrap.Modal(document.getElementById('createBudgetModal')).show();
        }
        
        function viewUserTransactions(userId) {
            fetch(`token_management_api.php?action=get_user_transactions&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('userTransactionsContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('userTransactionsModal')).show();
                    } else {
                        alert('Error loading user transactions: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading user transactions');
                });
        }

        function viewUserBudget(userId) {
            fetch(`token_management_api.php?action=get_user_budget&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('userBudgetContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('userBudgetModal')).show();
                    } else {
                        alert('Error loading user budget: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading user budget');
                });
        }
        
        function viewBudgetTransactions(budgetId) {
            fetch(`token_management_api.php?action=get_budget_transactions&budget_id=${budgetId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('budgetTransactionsContent').innerHTML = data.html;
                        new bootstrap.Modal(document.getElementById('budgetTransactionsModal')).show();
                    } else {
                        alert('Error loading budget transactions: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading budget transactions');
                });
        }
        
        // Handle create budget form submission
        document.getElementById('createBudgetForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('action', 'create_budget');
            
            fetch('token_management_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('createBudgetModal')).hide();
                    alert('Budget created successfully!');
                    location.reload(); // Refresh to show new budget
                } else {
                    alert('Error creating budget: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error creating budget');
            });
        });
        
        // Clean URL after showing message
        if (window.location.search.includes('msg=')) {
            const cleanUrl = window.location.pathname;
            window.history.replaceState({}, document.title, cleanUrl);
        }
    </script>
</body>
</html>
