<?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 'edit_package':
                $message = handleEditPackage($pdo, $_POST);
                break;
            case 'delete_package':
                $message = handleDeletePackage($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 handleEditPackage($pdo, $data) {
    try {
        $stmt = $pdo->prepare("
            UPDATE token_packages 
            SET name = ?, description = ?, token_amount = ?, price = ?, bonus_tokens = ?, sort_order = ?
            WHERE id = ?
        ");
        
        $stmt->execute([
            $data['package_name'],
            $data['package_description'],
            $data['token_amount'],
            $data['price'],
            $data['bonus_tokens'] ?? 0,
            $data['sort_order'] ?? 0,
            $data['package_id']
        ]);
        
        return "success: Token package updated successfully";
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleDeletePackage($pdo, $data) {
    try {
        // Check if package is being used in any transactions or orders first
        $usage_check = $pdo->prepare("
            SELECT COUNT(*) as usage_count 
            FROM token_transactions 
            WHERE description LIKE CONCAT('%Package: ', (SELECT name FROM token_packages WHERE id = ?), '%')
        ");
        $usage_check->execute([$data['package_id']]);
        $usage = $usage_check->fetch(PDO::FETCH_ASSOC);
        
        if ($usage['usage_count'] > 0) {
            return "error: Cannot delete package as it has been used in {$usage['usage_count']} transactions";
        }
        
        $stmt = $pdo->prepare("DELETE FROM token_packages WHERE id = ?");
        $stmt->execute([$data['package_id']]);
        
        return "success: Token package deleted 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'; ?>
    <!-- Removed Font Awesome; using Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        /* Token Management Manual Styles */
        .manual-content {
            font-size: 14px;
            line-height: 1.6;
        }
        .manual-content h1 {
            border-bottom: 3px solid #007bff;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .manual-content h2 {
            border-bottom: 2px solid #28a745;
            padding-bottom: 8px;
            margin-top: 30px;
            margin-bottom: 15px;
        }
        .manual-content h3 {
            margin-top: 25px;
            margin-bottom: 12px;
            color: #007bff;
        }
        .manual-content pre {
            border-left: 4px solid #007bff;
            font-size: 12px;
        }
        .manual-content code:not(pre code) {
            color: #d63384;
            background-color: #f8f9fa;
        }
        .manual-content .table {
            font-size: 12px;
        }
        .manual-content ul {
            padding-left: 20px;
        }
        .manual-content li {
            margin-bottom: 5px;
        }
        #tokenManagementHelpModal .modal-dialog {
            max-width: 95vw;
        }
        #tokenManagementHelpModal .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        .table-of-contents {
            max-height: 60vh;
            overflow-y: auto;
        }
        .list-group-item-action:hover {
            background-color: #e3f2fd;
        }
        /* Smooth scrolling for anchor links */
        html {
            scroll-behavior: smooth;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <div class="row">
            <div class="col-12">
               
                    <!-- Help Modal -->
                    <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-xl modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="helpModalLabel">
                                        <i data-lucide="help-circle" class="me-2 text-info" style="width: 16px; height: 16px;"></i>Token Management Help
                                    </h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body p-0" style="height:80vh;">
                                    <iframe src="../help/token_management_help.html" style="width:100%;height:100%;border:0;" title="Token Management Help"></iframe>
                                </div>
                            </div>
                        </div>
                    </div>
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="mb-1">
                            <i data-lucide="coins" class="text-warning me-2" style="width: 20px; height: 20px;"></i>Token Management
                        </h2>
                        <p class="text-muted mb-0">Manage credits, pricing, and budget controls</p>
                    </div>
                    <div class="d-flex align-items-center gap-3">
                        <button class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#helpModal" title="Help & Guide">
                        <i data-lucide="help-circle" class="me-1" style="width: 16px; height: 16px;"></i> Help
                    </button>
                        <button class="btn btn-outline-info" onclick="showTokenManagementHelp()" title="View Complete Manual">
                            <i data-lucide="help-circle" class="me-2" style="width: 16px; height: 16px;"></i>System Manual
                        </button>
                        <span class="badge bg-warning fs-6">Total Balance: <?= number_format($budget_stats['total_balance'], 2) ?> tokens</span>
                    </div>
                </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 data-lucide="<?= $msg_type === 'success' ? 'check-circle' : 'alert-triangle' ?>" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="coins" class="text-warning mb-2" style="width: 32px; height: 32px;"></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 data-lucide="list-checks" class="text-primary mb-2" style="width: 32px; height: 32px;"></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 data-lucide="arrow-left-right" class="text-success mb-2" style="width: 32px; height: 32px;"></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 data-lucide="trending-up" class="text-info mb-2" style="width: 32px; height: 32px;"></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 data-lucide="list-checks" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="package" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="wallet" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="code" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="pie-chart" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="users" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="help-circle" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="plus" class="me-2" style="width: 16px; height: 16px;"></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 data-lucide="coins" class="me-1" style="width: 14px; height: 14px;"></i><?= number_format($action['token_cost'], 2) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?= getCategoryColor($action['category']) ?>">
                                                    <?= ucfirst($action['category']) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <i data-lucide="circle" class="text-<?= $action['is_active'] ? 'success' : 'danger' ?>" style="width: 14px; height: 14px;"></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 data-lucide="edit" style="width: 14px; height: 14px;"></i>
                                                    </button>
                                                    <button class="btn btn-outline-info" onclick="viewCode('<?= htmlspecialchars($action['action_name']) ?>')">
                                                        <i data-lucide="code" style="width: 14px; height: 14px;"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" onclick="deleteAction(<?= $action['id'] ?>)">
                                                        <i data-lucide="trash-2" style="width: 14px; height: 14px;"></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 data-lucide="plus" style="width: 16px; height: 16px;"></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 data-lucide="edit" style="width: 14px; height: 14px;"></i>
                                                </button>
                                                <button class="btn btn-outline-danger btn-sm" onclick="deletePackage(<?= $package['id'] ?>)">
                                                    <i data-lucide="trash-2" style="width: 14px; height: 14px;"></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 data-lucide="plus" style="width: 16px; height: 16px;"></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 data-lucide="history" style="width: 14px; height: 14px;"></i>View History
                                                </button>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-success" onclick="addTokensToUser(<?= $user['id'] ?>)">
                                                        <i data-lucide="plus" style="width: 14px; height: 14px;"></i>
                                                    </button>
                                                    <button class="btn btn-outline-primary" onclick="viewUserBudget(<?= $user['id'] ?>)">
                                                        <i data-lucide="eye" style="width: 14px; height: 14px;"></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 data-lucide="code" style="width: 16px; height: 16px;"></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 data-lucide="shield-check" style="width: 16px; height: 16px;"></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 data-lucide="wand" style="width: 16px; height: 16px;"></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 data-lucide="tag" style="width: 14px; height: 14px;"></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 data-lucide="pie-chart" style="width: 16px; height: 16px;"></i>Token System Overview
                                <button class="btn btn-sm btn-outline-primary float-end" onclick="refreshOverviewData()">
                                    <i data-lucide="refresh-cw" style="width: 14px; height: 14px;"></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 data-lucide="wallet" style="width: 16px; height: 16px;"></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 data-lucide="users" style="width: 14px; height: 14px;"></i>Group
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="badge bg-success">
                                                                            <i data-lucide="user" style="width: 14px; height: 14px;"></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 data-lucide="history" style="width: 14px; height: 14px;"></i>Transactions
                                                                    </button>
                                                                    <?php if ($budget['group_id']): ?>
                                                                    <button class="btn btn-sm btn-outline-info" onclick="viewGroupMembers(<?= $budget['group_id'] ?>)">
                                                                        <i data-lucide="users" style="width: 14px; height: 14px;"></i>Members
                                                                    </button>
                                                                    <?php endif; ?>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="8" class="text-center text-muted py-4">
                                                                    <i data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="arrow-left-right" style="width: 16px; height: 16px;"></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' => 'plus',
                                                                        'debit' => 'minus',
                                                                        'purchase' => 'shopping-cart',
                                                                        'refund' => 'undo',
                                                                        'adjustment' => 'edit'
                                                                    ];
                                                                    $color = $type_colors[$tx['transaction_type']] ?? 'secondary';
                                                                    $icon = $type_icons[$tx['transaction_type']] ?? 'circle';
                                                                    ?>
                                                                    <span class="badge bg-<?= $color ?>">
                                                                        <i data-lucide="<?= $icon ?>" style="width: 14px; height: 14px;"></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 data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="bar-chart" style="width: 16px; height: 16px;"></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 data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="users" style="width: 16px; height: 16px;"></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 data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="download" style="width: 16px; height: 16px;"></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 data-lucide="file-spreadsheet" style="width: 16px; height: 16px;"></i>All Transactions CSV
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-success w-100" onclick="exportAllBudgets()">
                                                        <i data-lucide="file-spreadsheet" style="width: 16px; height: 16px;"></i>All Budgets Excel
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-warning w-100" onclick="exportActionUsage()">
                                                        <i data-lucide="bar-chart" style="width: 16px; height: 16px;"></i>Action Usage Report
                                                    </button>
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-outline-info w-100" onclick="exportUserActivity()">
                                                        <i data-lucide="users" style="width: 16px; height: 16px;"></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 data-lucide="users" style="width: 16px; height: 16px;"></i>Group Members Management
                                <button class="btn btn-sm btn-outline-success float-end" data-bs-toggle="modal" data-bs-target="#addGroupModal">
                                    <i data-lucide="plus" style="width: 14px; height: 14px;"></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 data-lucide="layers" style="width: 16px; height: 16px;"></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 data-lucide="eye" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                        <button class="btn btn-outline-info" onclick="manageGroupMembers(<?= $group['id'] ?>)" title="Manage Members">
                                                                            <i data-lucide="user-cog" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                        <?php if (!$group['budget_id']): ?>
                                                                        <button class="btn btn-outline-success" onclick="createGroupBudget(<?= $group['id'] ?>)" title="Create Budget">
                                                                            <i data-lucide="wallet" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                        <?php endif; ?>
                                                                        <button class="btn btn-outline-warning" onclick="editGroup(<?= $group['id'] ?>)" title="Edit Group">
                                                                            <i data-lucide="edit" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="6" class="text-center text-muted py-4">
                                                                    <i data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="address-book" style="width: 16px; height: 16px;"></i>Detailed Group Memberships
                                                <button class="btn btn-sm btn-outline-light float-end" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                                                    <i data-lucide="user-plus" style="width: 14px; height: 14px;"></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 data-lucide="user-pen" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                        <button class="btn btn-outline-danger" onclick="removeFromGroup(<?= $membership['group_id'] ?>, <?= $membership['user_id'] ?>)" title="Remove from Group">
                                                                            <i data-lucide="user-minus" style="width: 14px; height: 14px;"></i>
                                                                        </button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="6" class="text-center text-muted py-4">
                                                                    <i data-lucide="info" style="width: 16px; height: 16px;"></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 data-lucide="database" style="width: 16px; height: 16px;"></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 data-lucide="settings" style="width: 16px; height: 16px;"></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 data-lucide="wrench" style="width: 16px; height: 16px;"></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 data-lucide="book" style="width: 16px; height: 16px;"></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 data-lucide="rocket" style="width: 16px; height: 16px;"></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 data-lucide="folder" style="width: 16px; height: 16px;"></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 data-lucide="plus" style="width: 18px; height: 18px;"></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 data-lucide="plus" style="width: 16px; height: 16px;"></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 data-lucide="package" style="width: 18px; height: 18px;"></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 data-lucide="plus" style="width: 16px; height: 16px;"></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 data-lucide="plus" style="width: 18px; height: 18px;"></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 data-lucide="plus" style="width: 16px; height: 16px;"></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 data-lucide="wallet" class="me-2" style="width:16px;height:16px;"></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 data-lucide="plus" class="me-2" style="width:16px;height:16px;"></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 data-lucide="history" class="me-2" style="width:16px;height:16px;"></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 data-lucide="download" class="me-2" style="width:16px;height:16px;"></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 data-lucide="users" class="me-2" style="width:16px;height:16px;"></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 data-lucide="plus" class="me-2" style="width:16px;height:16px;"></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 data-lucide="user-plus" class="me-2" style="width:16px;height:16px;"></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 data-lucide="user-plus" class="me-2" style="width:16px;height:16px;"></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;

        document.addEventListener('DOMContentLoaded', () => {
            if (window.lucide) {
                lucide.createIcons();
            }
        });

        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 data-lucide="alert-triangle" class="me-2" style="width:16px;height:16px;"></i>
                                ${data.message || 'Unable to load transactions'}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('transactionContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i data-lucide="alert-circle" class="me-2" style="width:16px;height:16px;"></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 data-lucide="alert-triangle" class="me-2" style="width:16px;height:16px;"></i>
                                ${data.message || 'Unable to load budget details'}
                                <button class="btn btn-primary btn-sm ms-3" onclick="createBudgetForUser(${userId})">
                                    <i data-lucide="plus" class="me-1" style="width:14px;height:14px;"></i>Create Budget
                                </button>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('budgetContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i data-lucide="alert-circle" class="me-2" style="width:16px;height:16px;"></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 data-lucide="info" class="me-2" style="width:16px;height:16px;"></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;
            if (window.lucide) lucide.createIcons();
        }

        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 data-lucide="user" class="me-2" style="width:16px;height:16px;"></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 data-lucide="wallet" class="me-2" style="width:16px;height:16px;"></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 data-lucide="info" class="me-2" style="width:16px;height:16px;"></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;
            if (window.lucide) lucide.createIcons();
        }

        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 data-lucide="alert-triangle" class="me-2" style="width:16px;height:16px;"></i>
                                No transactions found for this budget: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    document.getElementById('transactionContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i data-lucide="alert-circle" class="me-2" style="width:16px;height:16px;"></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 data-lucide="info" class="me-2" style="width:16px;height:16px;"></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;
            if (window.lucide) lucide.createIcons();
        }
        
        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) {
            // Find the action data from the page
            const actionRow = document.querySelector(`button[onclick="editAction(${actionId})"]`).closest('tr');
            const cells = actionRow.querySelectorAll('td');
            
            // Extract action data
            const actionName = cells[0].textContent.trim();
            const description = cells[1].textContent.trim();
            const tokenCost = cells[2].querySelector('.badge').textContent.replace(/[^\d.]/g, '');
            const category = cells[3].querySelector('.badge').textContent.trim().toLowerCase();
            const isActive = cells[4].textContent.includes('Active');
            
            // Create edit modal
            const modalHtml = `
                <div class="modal fade" id="editActionModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i data-lucide="edit" style="width: 18px; height: 18px;"></i>Edit Token Action
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form method="post">
                                <input type="hidden" name="action" value="edit_action">
                                <input type="hidden" name="action_id" value="${actionId}">
                                <div class="modal-body">
                                    <div class="mb-3">
                                        <label class="form-label">Action Name</label>
                                        <input type="text" class="form-control" value="${actionName}" readonly>
                                        <div class="form-text">Action name cannot be changed</div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Description *</label>
                                        <textarea class="form-control" name="action_description" rows="3" required>${description}</textarea>
                                    </div>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Token Cost *</label>
                                            <input type="number" class="form-control" name="token_cost" step="0.01" value="${tokenCost}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Category *</label>
                                            <select class="form-select" name="category" required>
                                                <option value="general" ${category === 'general' ? 'selected' : ''}>General</option>
                                                <option value="participants" ${category === 'participants' ? 'selected' : ''}>Participants</option>
                                                <option value="judges" ${category === 'judges' ? 'selected' : ''}>Judges</option>
                                                <option value="events" ${category === 'events' ? 'selected' : ''}>Events</option>
                                                <option value="reports" ${category === 'reports' ? 'selected' : ''}>Reports</option>
                                                <option value="communications" ${category === 'communications' ? 'selected' : ''}>Communications</option>
                                                <option value="premium" ${category === 'premium' ? 'selected' : ''}>Premium</option>
                                                <option value="scoring" ${category === 'scoring' ? 'selected' : ''}>Scoring</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-check mt-3">
                                        <input class="form-check-input" type="checkbox" name="is_active" id="editIsActive" ${isActive ? 'checked' : ''}>
                                        <label class="form-check-label" for="editIsActive">
                                            Active (can be used for charging tokens)
                                        </label>
                                    </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 data-lucide="save" class="me-2" style="width:16px;height:16px;"></i>Update Action
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing modal if present
            const existingModal = document.getElementById('editActionModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Add modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            if (window.lucide) lucide.createIcons();
            
            // Show modal
            new bootstrap.Modal(document.getElementById('editActionModal')).show();
        }
        
        function viewCode(actionName) {
            // Create code view modal
            const modalHtml = `
                <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">
                                    <i data-lucide="code" style="width: 18px; height: 18px;"></i>Integration Code for: ${actionName}
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-4">
                                    <h6 class="text-primary">Basic Usage:</h6>
                                    <pre class="bg-light border rounded p-3"><code>// Charge tokens for this action
$result = TokenSystem::charge('${actionName}', $user_id);
if (!$result['success']) {
    // Handle insufficient tokens
    echo $result['message'];
    exit;
}</code></pre>
                                </div>
                                
                                <div class="mb-4">
                                    <h6 class="text-success">With Reference Data:</h6>
                                    <pre class="bg-light border rounded p-3"><code>// Charge with additional context
$result = TokenSystem::charge('${actionName}', $user_id, [
    'event_id' => $event_id,
    'reference_type' => 'event'
]);
if (!$result['success']) {
    echo $result['message'];
    exit;
}</code></pre>
                                </div>
                                
                                <div class="mb-4">
                                    <h6 class="text-warning">Pre-check Balance:</h6>
                                    <pre class="bg-light border rounded p-3"><code>// Check if user can afford this action
if (!TokenSystem::canAfford('${actionName}', $user_id)) {
    $balance = TokenSystem::getBalance($user_id);
    echo "Insufficient tokens. Current balance: $balance";
    exit;
}</code></pre>
                                </div>
                                
                                <div class="mb-3">
                                    <h6 class="text-info">AJAX Integration:</h6>
                                    <pre class="bg-light border rounded p-3"><code>// JavaScript AJAX call
fetch('api/token_charge.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        action: '${actionName}',
        user_id: userId,
        reference_data: { /* your data */ }
    })
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('Tokens charged successfully');
    } else {
        alert('Error: ' + data.message);
    }
});</code></pre>
                                </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="copyCodeToClipboard('${actionName}')">
                                    <i data-lucide="copy" class="me-2" style="width:16px;height:16px;"></i>Copy Basic Code
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing modal if present
            const existingModal = document.getElementById('viewCodeModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Add modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            if (window.lucide) lucide.createIcons();
            
            // Show modal
            new bootstrap.Modal(document.getElementById('viewCodeModal')).show();
        }
        
        function copyCodeToClipboard(actionName) {
            const code = `$result = TokenSystem::charge('${actionName}', $user_id);
if (!$result['success']) {
    echo $result['message'];
    exit;
}`;
            
            navigator.clipboard.writeText(code).then(() => {
                alert('Code copied to clipboard!');
            }).catch(() => {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = code;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                alert('Code copied to clipboard!');
            });
        }
        
        function deleteAction(actionId) {
            if (confirm('Are you sure you want to delete this action? This cannot be undone.')) {
                // Create a form and submit it
                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 editPackage(packageId) {
            // Find the package data from the page
            const packageCard = document.querySelector(`button[onclick="editPackage(${packageId})"]`).closest('.card');
            
            // Extract package data
            const name = packageCard.querySelector('.card-header h6').textContent.trim();
            const price = packageCard.querySelector('.display-6').textContent.replace('$', '').trim();
            const tokenAmount = packageCard.querySelector('.badge.bg-warning').textContent.replace(/[^\d]/g, '');
            const bonusTokens = packageCard.querySelector('.badge.bg-success')?.textContent.replace(/[^\d]/g, '') || '0';
            const description = packageCard.querySelector('.text-muted').textContent.trim();
            
            // Create edit modal
            const modalHtml = `
                <div class="modal fade" id="editPackageModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <i data-lucide="edit" style="width: 18px; height: 18px;"></i>Edit Token Package
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form method="post">
                                <input type="hidden" name="action" value="edit_package">
                                <input type="hidden" name="package_id" value="${packageId}">
                                <div class="modal-body">
                                    <div class="mb-3">
                                        <label class="form-label">Package Name *</label>
                                        <input type="text" class="form-control" name="package_name" value="${name}" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="package_description" rows="3">${description}</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" value="${tokenAmount}" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Price *</label>
                                            <input type="number" class="form-control" name="price" step="0.01" value="${price}" 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="${bonusTokens}">
                                        </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 data-lucide="save" class="me-2" style="width:16px;height:16px;"></i>Update Package
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing modal if present
            const existingModal = document.getElementById('editPackageModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Add modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            
            // Show modal
            new bootstrap.Modal(document.getElementById('editPackageModal')).show();
        }
        
        function deletePackage(packageId) {
            if (confirm('Are you sure you want to delete this package? This cannot be undone.')) {
                // Create a form and submit it
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_package">
                    <input type="hidden" name="package_id" value="${packageId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        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');
            });
        });
        
        // Token Management Help Functions
        function showTokenManagementHelp() {
            const modal = new bootstrap.Modal(document.getElementById('tokenManagementHelpModal'));
            modal.show();
            
            // Load the markdown file and convert to HTML
            fetch('TOKEN_MANAGEMENT_MANUAL.md')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Manual file not found');
                    }
                    return response.text();
                })
                .then(markdown => {
                    const htmlContent = convertMarkdownToHTML(markdown);
                    document.getElementById('helpContent').innerHTML = htmlContent;
                })
                .catch(error => {
                    console.error('Error loading manual:', error);
                    document.getElementById('helpContent').innerHTML = `
                        <div class="alert alert-warning">
                            <h5><i data-lucide="alert-triangle" class="me-2" style="width:16px;height:16px;"></i>Manual Loading Failed</h5>
                            <p>Unable to load the Token Management Manual. Please contact your administrator.</p>
                            <p class="small text-muted">Error: ${error.message}</p>
                        </div>
                    `;
                });
        }
        
        function convertMarkdownToHTML(markdown) {
            // Simple markdown to HTML converter for basic formatting
            let html = markdown
                // Headers with anchor IDs
                .replace(/^### (.*$)/gim, function(match, title) {
                    const id = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
                    return `<h3 id="${id}" class="text-primary mt-4 mb-3">${title}</h3>`;
                })
                .replace(/^## (.*$)/gim, function(match, title) {
                    const id = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
                    return `<h2 id="${id}" class="text-success mt-4 mb-3">${title}</h2>`;
                })
                .replace(/^# (.*$)/gim, function(match, title) {
                    const id = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
                    return `<h1 id="${id}" class="text-dark mt-4 mb-3">${title}</h1>`;
                })
                
                // Code blocks
                .replace(/```php\n([\s\S]*?)\n```/g, '<div class="code-block mb-3"><small class="badge bg-primary">PHP</small><pre class="bg-light border rounded p-3 mt-1"><code class="language-php">$1</code></pre></div>')
                .replace(/```javascript\n([\s\S]*?)\n```/g, '<div class="code-block mb-3"><small class="badge bg-warning text-dark">JavaScript</small><pre class="bg-light border rounded p-3 mt-1"><code class="language-javascript">$1</code></pre></div>')
                .replace(/```sql\n([\s\S]*?)\n```/g, '<div class="code-block mb-3"><small class="badge bg-info">SQL</small><pre class="bg-light border rounded p-3 mt-1"><code class="language-sql">$1</code></pre></div>')
                .replace(/```bash\n([\s\S]*?)\n```/g, '<div class="code-block mb-3"><small class="badge bg-dark">Bash</small><pre class="bg-dark text-light rounded p-3 mt-1"><code class="language-bash">$1</code></pre></div>')
                .replace(/```\n([\s\S]*?)\n```/g, '<pre class="bg-light border rounded p-3 mb-3"><code>$1</code></pre>')
                
                // Inline code
                .replace(/`([^`]+)`/g, '<code class="bg-light px-2 py-1 rounded text-danger">$1</code>')
                
                // Bold and italic
                .replace(/\*\*(.*?)\*\*/g, '<strong class="text-primary">$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                
                // Links (basic)
                .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-decoration-none text-primary">$1 <i data-lucide="external-link" style="width:12px;height:12px;vertical-align:middle;"></i></a>')
                
                // Lists
                .replace(/^\s*- (.*$)/gim, '<li class="mb-2">$1</li>')
                .replace(/^\s*\d+\. (.*$)/gim, '<li class="mb-2">$1</li>')
                
                // Line breaks
                .replace(/\n\n/g, '</p><p class="mb-3">')
                .replace(/\n/g, '<br>')
                
                // Wrap in paragraphs
                .replace(/^([^<].*$)/gim, '<p class="mb-3">$1</p>');
            
            // Clean up and wrap lists
            html = html.replace(/(<li.*?<\/li>)/gs, function(match) {
                return '<ul class="list-unstyled ms-3 mb-3">' + match + '</ul>';
            });
            
            // Add some Bootstrap styling
            html = html.replace(/<table>/g, '<div class="table-responsive"><table class="table table-striped table-hover table-sm">');
            html = html.replace(/<\/table>/g, '</table></div>');
            html = html.replace(/<blockquote>/g, '<blockquote class="blockquote border-start border-primary border-4 ps-3 ms-3">');
            
            // Add section dividers
            html = html.replace(/<h2/g, '<hr class="my-4"><h2');
            
            return `
                <div class="container-fluid container-StyleScore p-4">
                    <div class="row">
                        <div class="col-3">
                            <div class="sticky-top table-of-contents" style="top: 20px;">
                                <h6 class="text-muted mb-3">
                                    <i data-lucide="list" class="me-2" style="width:16px;height:16px;"></i>Table of Contents
                                </h6>
                                <div class="list-group list-group-flush">
                                    <a href="#overview" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="info" class="me-2 text-primary" style="width:16px;height:16px;"></i>Overview
                                    </a>
                                    <a href="#quick-start-guide" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="rocket" class="me-2 text-success" style="width:16px;height:16px;"></i>Quick Start Guide
                                    </a>
                                    <a href="#token-actions-management" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="list-checks" class="me-2 text-warning" style="width:16px;height:16px;"></i>Token Actions Management
                                    </a>
                                    <a href="#token-packages-management" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="package" class="me-2 text-info" style="width:16px;height:16px;"></i>Token Packages Management
                                    </a>
                                    <a href="#budget-management" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="wallet" class="me-2 text-secondary" style="width:16px;height:16px;"></i>Budget Management
                                    </a>
                                    <a href="#code-generator" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="code" style="width: 16px; height: 16px;"></i>Code Generator
                                    </a>
                                    <a href="#system-overview" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="pie-chart" class="me-2 text-danger" style="width:16px;height:16px;"></i>System Overview
                                    </a>
                                    <a href="#group-management" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="users" class="me-2 text-success" style="width:16px;height:16px;"></i>Group Management
                                    </a>
                                    <a href="#php-backend-functions" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="code" class="me-2 text-primary" style="width:16px;height:16px;"></i>PHP Backend Functions
                                    </a>
                                    <a href="#javascript-functions" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="code-xml" class="me-2 text-warning" style="width:16px;height:16px;"></i>JavaScript Functions
                                    </a>
                                    <a href="#database-schema" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="database" class="me-2 text-info" style="width:16px;height:16px;"></i>Database Schema
                                    </a>
                                    <a href="#api-integration" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="plug" class="me-2 text-secondary" style="width:16px;height:16px;"></i>API Integration
                                    </a>
                                    <a href="#troubleshooting" class="list-group-item list-group-item-action py-2 border-0">
                                        <i data-lucide="wrench" class="me-2 text-danger" style="width:16px;height:16px;"></i>Troubleshooting
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="col-9">
                            <div class="manual-content">
                                ${html}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function downloadManual() {
            // Create a download link for the markdown file
            const link = document.createElement('a');
            link.href = 'TOKEN_MANAGEMENT_MANUAL.md';
            link.download = 'Token_Management_Manual.md';
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        function printManual() {
            // Open print dialog for the manual content
            const printWindow = window.open('', '_blank');
            const helpContent = document.getElementById('helpContent').innerHTML;
            
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Token Management Manual</title>
                    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
                    <style>
                        body { font-family: Arial, sans-serif; }
                        .no-print { display: none; }
                        pre { font-size: 10px; }
                        h1, h2, h3 { page-break-after: avoid; }
                        @media print {
                            .container-fluid .row .col-3 { display: none; }
                            .container-fluid .row .col-9 { width: 100%; }
                        }
                    </style>
                </head>
                <body>
                    <div class="container-fluid container-StyleScore p-4">
                        <h1 class="text-center mb-4">Token Management System Manual</h1>
                        ${helpContent}
                    </div>
                </body>
                </html>
            `);
            
            printWindow.document.close();
            printWindow.print();
        }
        
        // Clean URL after showing message
        if (window.location.search.includes('msg=')) {
            const cleanUrl = window.location.pathname;
            window.history.replaceState({}, document.title, cleanUrl);
        }
    </script>

    <!-- Token Management Help Modal -->
    <div class="modal fade" id="tokenManagementHelpModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">
                        <i data-lucide="book" class="me-2" style="width:16px;height:16px;"></i>Token Management System - Complete Manual
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <div id="helpContent" class="p-4">
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading manual...</span>
                            </div>
                            <p class="mt-3 text-muted">Loading Token Management Manual...</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="downloadManual()">
                        <i data-lucide="download" class="me-2" style="width:16px;height:16px;"></i>Download Manual (PDF)
                    </button>
                    <button type="button" class="btn btn-success" onclick="printManual()">
                        <i data-lucide="printer" class="me-2" style="width:16px;height:16px;"></i>Print Manual
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'footer.php'; ?>
</body>
</html>
