<?php
session_start();
require_once '../includes/db.php';

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'get_group_details':
            handleGetGroupDetails();
            break;
        
        case 'get_group_members':
            handleGetGroupMembers();
            break;
        
        case 'manage_group_members':
            handleManageGroupMembers();
            break;
        
        case 'get_user_transactions':
            handleGetUserTransactions();
            break;
        
        case 'get_user_budget':
            handleGetUserBudget();
            break;
        
        case 'get_budget_transactions':
            handleGetBudgetTransactions();
            break;
        
        case 'create_budget':
            handleCreateBudget();
            break;
        
        case 'add_group_member':
            handleAddGroupMember();
            break;
        
        case 'remove_group_member':
            handleRemoveGroupMember();
            break;
        
        case 'update_member_role':
            handleUpdateMemberRole();
            break;
        
        case 'edit_action':
        $action_id = $_POST['action_id'] ?? 0;
        $description = $_POST['action_description'] ?? '';
        $token_cost = $_POST['token_cost'] ?? 0;
        $category = $_POST['category'] ?? '';
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE token_actions SET description = ?, token_cost = ?, category = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
        $result = $stmt->execute([$description, $token_cost, $category, $is_active, $action_id]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Action updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update action']);
        }
        break;

    case 'get_action_code':
        $action_id = $_GET['action_id'] ?? 0;
        $stmt = $pdo->prepare("SELECT * FROM token_actions WHERE id = ?");
        $stmt->execute([$action_id]);
        $action = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($action) {
            // Add a generic code template if no specific code exists
            $action['code'] = $action['code'] ?? "// Token action: {$action['action_name']}\n// Cost: {$action['token_cost']} tokens\n// Category: {$action['category']}\n\n// Example implementation:\nif (\$user_tokens >= {$action['token_cost']}) {\n    // Perform action logic here\n    deduct_tokens(\$user_id, {$action['token_cost']}, '{$action['action_name']}');\n    return true;\n} else {\n    throw new Exception('Insufficient tokens');\n}";
            
            echo json_encode(['success' => true, 'data' => $action]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Action not found']);
        }
        break;

    case 'get_package':
        $package_id = $_GET['package_id'] ?? 0;
        $stmt = $pdo->prepare("SELECT * FROM token_packages WHERE id = ?");
        $stmt->execute([$package_id]);
        $package = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($package) {
            echo json_encode(['success' => true, 'data' => $package]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Package not found']);
        }
        break;

    case 'edit_package':
        $package_id = $_POST['package_id'] ?? 0;
        $name = $_POST['package_name'] ?? '';
        $description = $_POST['package_description'] ?? '';
        $token_amount = $_POST['token_amount'] ?? 0;
        $price = $_POST['price'] ?? 0;
        $bonus_tokens = $_POST['bonus_tokens'] ?? 0;
        $sort_order = $_POST['sort_order'] ?? 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE token_packages SET name = ?, description = ?, token_amount = ?, price = ?, bonus_tokens = ?, sort_order = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
        $result = $stmt->execute([$name, $description, $token_amount, $price, $bonus_tokens, $sort_order, $is_active, $package_id]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Package updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update package']);
        }
        break;

    case 'get_user_transactions':
        $user_id = $_GET['user_id'] ?? 0;
        $stmt = $pdo->prepare("
            SELECT tt.*, ta.action_name 
            FROM token_transactions tt 
            LEFT JOIN token_actions ta ON tt.reference_type = 'action' AND tt.reference_id = ta.id 
            WHERE tt.user_id = ? 
            ORDER BY tt.created_at DESC
        ");
        $stmt->execute([$user_id]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'data' => $transactions]);
        break;

    case 'get_user_budget':
        $user_id = $_GET['user_id'] ?? 0;
        
        // Get user basic info
        $stmt = $pdo->prepare("SELECT username, full_name, created_at FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            break;
        }
        
        // Get token balance and transaction summary
        $stmt = $pdo->prepare("
            SELECT 
                COALESCE(SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END), 0) as total_credits,
                COALESCE(SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END), 0) as total_debits,
                COUNT(*) as transaction_count,
                MAX(created_at) as last_transaction
            FROM token_transactions 
            WHERE user_id = ?
        ");
        $stmt->execute([$user_id]);
        $summary = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Calculate current balance
        $token_balance = $summary['total_credits'] - $summary['total_debits'];
        
        $budget = array_merge($user, $summary, ['token_balance' => $token_balance]);
        
        echo json_encode(['success' => true, 'data' => $budget]);
        break;

    case 'add_group_member':
        $group_id = $_POST['group_id'] ?? 0;
        $user_id = $_POST['user_id'] ?? 0;
        
        // Check if already a member
        $stmt = $pdo->prepare("SELECT id FROM group_members WHERE group_id = ? AND user_id = ?");
        $stmt->execute([$group_id, $user_id]);
        
        if ($stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'User is already a member of this group']);
            break;
        }
        
        $stmt = $pdo->prepare("INSERT INTO group_members (group_id, user_id, role, joined_at) VALUES (?, ?, 'member', NOW())");
        $result = $stmt->execute([$group_id, $user_id]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Member added successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to add member']);
        }
        break;

    case 'remove_group_member':
        $group_id = $_POST['group_id'] ?? 0;
        $user_id = $_POST['user_id'] ?? 0;
        
        $stmt = $pdo->prepare("DELETE FROM group_members WHERE group_id = ? AND user_id = ?");
        $result = $stmt->execute([$group_id, $user_id]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Member removed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to remove member']);
        }
        break;

    default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    error_log("Token Management API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}

function handleGetGroupDetails() {
    global $pdo;
    
    $group_id = $_GET['group_id'] ?? 0;
    
    $stmt = $pdo->prepare("
        SELECT 
            g.*,
            COUNT(ugm.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.total_spent as budget_spent,
            b.total_purchased as budget_purchased,
            b.id as budget_id,
            cb.username as created_by_name,
            cb.id as created_by_id
        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.id = ? AND g.is_active = 1
        GROUP BY g.id
    ");
    
    $stmt->execute([$group_id]);
    $group = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$group) {
        echo json_encode(['success' => false, 'message' => 'Group not found']);
        return;
    }
    
    // Get recent transactions for this group
    $trans_stmt = $pdo->prepare("
        SELECT 
            t.*,
            u.username,
            p.full_name,
            ta.action_name
        FROM token_transactions t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN token_actions ta ON t.action_id = ta.id
        WHERE t.budget_id = ?
        ORDER BY t.created_at DESC
        LIMIT 10
    ");
    $trans_stmt->execute([$group['budget_id']]);
    $recent_transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $html = generateGroupDetailsHTML($group, $recent_transactions);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateGroupDetailsHTML($group, $transactions) {
    $budget_status = $group['group_budget'] ? 'Active' : 'No Budget';
    $budget_color = $group['group_budget'] > 50 ? 'success' : ($group['group_budget'] > 10 ? 'warning' : 'danger');
    
    $html = "
    <div class='row'>
        <div class='col-md-6'>
            <div class='card border-0 bg-light'>
                <div class='card-body'>
                    <h6 class='card-title'>
                        <div class='d-flex align-items-center'>
                            <div class='color-box me-2' style='width: 20px; height: 20px; background-color: {$group['color']}; border-radius: 4px;'></div>
                            {$group['name']}
                        </div>
                    </h6>
                    <p class='card-text text-muted'>{$group['description']}</p>
                    <div class='row g-3'>
                        <div class='col-sm-6'>
                            <strong>Members:</strong><br>
                            <span class='badge bg-primary'>{$group['member_count']} members</span>
                        </div>
                        <div class='col-sm-6'>
                            <strong>Created:</strong><br>
                            " . date('M j, Y', strtotime($group['created_at'])) . "
                        </div>
                        <div class='col-sm-6'>
                            <strong>Created By:</strong><br>
                            {$group['created_by_name']}
                        </div>
                        <div class='col-sm-6'>
                            <strong>Status:</strong><br>
                            <span class='badge bg-success'>Active</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class='col-md-6'>
            <div class='card border-0 bg-light'>
                <div class='card-body'>
                    <h6 class='card-title'>Budget Information</h6>";
    
    if ($group['group_budget']) {
        $html .= "
                    <div class='row g-3'>
                        <div class='col-sm-6'>
                            <strong>Current Balance:</strong><br>
                            <span class='badge bg-{$budget_color} fs-6'>" . number_format($group['group_budget'], 2) . " tokens</span>
                        </div>
                        <div class='col-sm-6'>
                            <strong>Total Spent:</strong><br>
                            <span class='text-danger'>" . number_format($group['budget_spent'], 2) . " tokens</span>
                        </div>
                        <div class='col-sm-6'>
                            <strong>Total Purchased:</strong><br>
                            <span class='text-success'>" . number_format($group['budget_purchased'], 2) . " tokens</span>
                        </div>
                        <div class='col-sm-6'>
                            <strong>Utilization:</strong><br>";
        
        $utilization = $group['budget_purchased'] > 0 ? ($group['budget_spent'] / $group['budget_purchased']) * 100 : 0;
        $html .= "<span class='text-info'>" . number_format($utilization, 1) . "%</span>
                        </div>
                    </div>";
    } else {
        $html .= "<p class='text-muted'>No budget assigned to this group.</p>
                  <button class='btn btn-outline-success btn-sm' onclick='createGroupBudget({$group['id']})'>
                      <i class='fas fa-wallet me-1'></i>Create Budget
                  </button>";
    }
    
    $html .= "
                </div>
            </div>
        </div>
    </div>";
    
    if (!empty($transactions)) {
        $html .= "
        <div class='mt-4'>
            <h6>Recent Transactions</h6>
            <div class='table-responsive'>
                <table class='table table-sm'>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>User</th>
                            <th>Action</th>
                            <th>Amount</th>
                            <th>Type</th>
                        </tr>
                    </thead>
                    <tbody>";
        
        foreach ($transactions as $trans) {
            $user_name = $trans['full_name'] ?: $trans['username'];
            $amount_class = $trans['transaction_type'] == 'credit' ? 'text-success' : 'text-danger';
            $amount_sign = $trans['transaction_type'] == 'credit' ? '+' : '-';
            
            $html .= "
                        <tr>
                            <td>" . date('M j, H:i', strtotime($trans['created_at'])) . "</td>
                            <td>{$user_name}</td>
                            <td>{$trans['action_name']}</td>
                            <td class='{$amount_class}'>{$amount_sign}" . number_format($trans['amount'], 2) . "</td>
                            <td><span class='badge bg-secondary'>{$trans['transaction_type']}</span></td>
                        </tr>";
        }
        
        $html .= "
                    </tbody>
                </table>
            </div>
            <div class='text-center'>
                <button class='btn btn-outline-primary btn-sm' onclick='viewBudgetTransactions({$group['budget_id']})'>
                    View All Transactions
                </button>
            </div>
        </div>";
    }
    
    return $html;
}

function handleGetGroupMembers() {
    global $pdo;
    
    $group_id = $_GET['group_id'] ?? 0;
    
    // Get group info
    $group_stmt = $pdo->prepare("SELECT * FROM user_groups WHERE id = ? AND is_active = 1");
    $group_stmt->execute([$group_id]);
    $group = $group_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$group) {
        echo json_encode(['success' => false, 'message' => 'Group not found']);
        return;
    }
    
    // Get members
    $members_stmt = $pdo->prepare("
        SELECT 
            ugm.*,
            u.username,
            p.full_name,
            p.email,
            ab.username as added_by_name
        FROM user_group_memberships ugm
        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 ugm.group_id = ?
        ORDER BY ugm.role_in_group DESC, p.full_name, u.username
    ");
    $members_stmt->execute([$group_id]);
    $members = $members_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $html = generateGroupMembersHTML($group, $members);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateGroupMembersHTML($group, $members) {
    $html = "
    <div class='mb-3'>
        <div class='d-flex align-items-center'>
            <div class='color-box me-2' style='width: 16px; height: 16px; background-color: {$group['color']}; border-radius: 3px;'></div>
            <h6 class='mb-0'>{$group['name']}</h6>
            <span class='badge bg-primary ms-2'>" . count($members) . " members</span>
        </div>
        <p class='text-muted mb-0'>{$group['description']}</p>
    </div>
    
    <div class='table-responsive'>
        <table class='table table-hover'>
            <thead>
                <tr>
                    <th>Member</th>
                    <th>Role</th>
                    <th>Joined</th>
                    <th>Added By</th>
                </tr>
            </thead>
            <tbody>";
    
    foreach ($members as $member) {
        $role_color = [
            'owner' => 'danger',
            'manager' => 'warning', 
            'member' => 'primary'
        ][$member['role_in_group']] ?? 'secondary';
        
        $html .= "
                <tr>
                    <td>
                        <div>
                            <strong>" . ($member['full_name'] ?: $member['username']) . "</strong>
                            <br><small class='text-muted'>@{$member['username']}</small>
                        </div>
                    </td>
                    <td>
                        <span class='badge bg-{$role_color}'>" . ucfirst($member['role_in_group']) . "</span>
                    </td>
                    <td>" . date('M j, Y', strtotime($member['joined_at'])) . "</td>
                    <td>" . ($member['added_by_name'] ?: 'System') . "</td>
                </tr>";
    }
    
    $html .= "
            </tbody>
        </table>
    </div>
    
    <div class='text-center mt-3'>
        <button class='btn btn-primary' onclick='manageGroupMembers({$group['id']})'>
            <i class='fas fa-users-cog me-1'></i>Manage Members
        </button>
    </div>";
    
    return $html;
}

function handleManageGroupMembers() {
    global $pdo;
    
    $group_id = $_GET['group_id'] ?? 0;
    
    // Get group info and current members
    $group_stmt = $pdo->prepare("SELECT * FROM user_groups WHERE id = ? AND is_active = 1");
    $group_stmt->execute([$group_id]);
    $group = $group_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$group) {
        echo json_encode(['success' => false, 'message' => 'Group not found']);
        return;
    }
    
    // Get current members
    $members_stmt = $pdo->prepare("
        SELECT 
            ugm.*,
            u.username,
            p.full_name
        FROM user_group_memberships ugm
        INNER JOIN users u ON ugm.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        WHERE ugm.group_id = ?
        ORDER BY ugm.role_in_group DESC, p.full_name, u.username
    ");
    $members_stmt->execute([$group_id]);
    $members = $members_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get available users to add
    $available_users_stmt = $pdo->prepare("
        SELECT 
            u.id,
            u.username,
            p.full_name
        FROM users u
        LEFT JOIN user_profiles p ON u.id = p.user_id
        WHERE u.id NOT IN (
            SELECT user_id FROM user_group_memberships WHERE group_id = ?
        )
        ORDER BY p.full_name, u.username
        LIMIT 50
    ");
    $available_users_stmt->execute([$group_id]);
    $available_users = $available_users_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $html = generateManageGroupMembersHTML($group, $members, $available_users);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateManageGroupMembersHTML($group, $members, $available_users) {
    $html = "
    <div class='row'>
        <div class='col-md-6'>
            <h6>Current Members</h6>
            <div class='list-group' style='max-height: 400px; overflow-y: auto;'>";
    
    foreach ($members as $member) {
        $role_color = [
            'owner' => 'danger',
            'manager' => 'warning', 
            'member' => 'primary'
        ][$member['role_in_group']] ?? 'secondary';
        
        $html .= "
                <div class='list-group-item d-flex justify-content-between align-items-center'>
                    <div>
                        <strong>" . ($member['full_name'] ?: $member['username']) . "</strong>
                        <br><small class='text-muted'>@{$member['username']}</small>
                    </div>
                    <div class='d-flex align-items-center'>
                        <select class='form-select form-select-sm me-2' style='width: auto;' onchange='updateMemberRole({$member['user_id']}, {$group['id']}, this.value)'>
                            <option value='member'" . ($member['role_in_group'] == 'member' ? ' selected' : '') . ">Member</option>
                            <option value='manager'" . ($member['role_in_group'] == 'manager' ? ' selected' : '') . ">Manager</option>
                            <option value='owner'" . ($member['role_in_group'] == 'owner' ? ' selected' : '') . ">Owner</option>
                        </select>
                        <button class='btn btn-outline-danger btn-sm' onclick='removeGroupMember({$member['user_id']}, {$group['id']})' title='Remove Member'>
                            <i class='fas fa-times'></i>
                        </button>
                    </div>
                </div>";
    }
    
    $html .= "
            </div>
        </div>
        <div class='col-md-6'>
            <h6>Add New Members</h6>
            <div class='mb-3'>
                <select class='form-select' id='newMemberSelect'>
                    <option value=''>Select a user to add...</option>";
    
    foreach ($available_users as $user) {
        $display_name = $user['full_name'] ?: $user['username'];
        $html .= "<option value='{$user['id']}'>{$display_name} (@{$user['username']})</option>";
    }
    
    $html .= "
                </select>
            </div>
            <div class='mb-3'>
                <label class='form-label'>Role</label>
                <select class='form-select' id='newMemberRole'>
                    <option value='member'>Member</option>
                    <option value='manager'>Manager</option>
                    <option value='owner'>Owner</option>
                </select>
            </div>
            <button class='btn btn-success' onclick='addGroupMember({$group['id']})'>
                <i class='fas fa-user-plus me-1'></i>Add Member
            </button>
        </div>
    </div>
    
    <script>
        function addGroupMember(groupId) {
            const userId = document.getElementById('newMemberSelect').value;
            const role = document.getElementById('newMemberRole').value;
            
            if (!userId) {
                alert('Please select a user to add');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'add_group_member');
            formData.append('group_id', groupId);
            formData.append('user_id', userId);
            formData.append('role', role);
            
            fetch('token_management_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Member added successfully!');
                    manageGroupMembers(groupId); // Refresh the modal
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error adding member');
            });
        }
        
        function removeGroupMember(userId, groupId) {
            if (!confirm('Are you sure you want to remove this member?')) return;
            
            const formData = new FormData();
            formData.append('action', 'remove_group_member');
            formData.append('group_id', groupId);
            formData.append('user_id', userId);
            
            fetch('token_management_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Member removed successfully!');
                    manageGroupMembers(groupId); // Refresh the modal
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error removing member');
            });
        }
        
        function updateMemberRole(userId, groupId, newRole) {
            const formData = new FormData();
            formData.append('action', 'update_member_role');
            formData.append('group_id', groupId);
            formData.append('user_id', userId);
            formData.append('role', newRole);
            
            fetch('token_management_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Optional: show success message
                    console.log('Role updated successfully');
                } else {
                    alert('Error: ' + data.message);
                    // Refresh to restore previous state
                    manageGroupMembers(groupId);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating role');
                manageGroupMembers(groupId);
            });
        }
    </script>";
    
    return $html;
}

function handleGetUserTransactions() {
    global $pdo;
    
    $user_id = $_GET['user_id'] ?? 0;
    
    // Get user info
    $user_stmt = $pdo->prepare("
        SELECT u.*, p.full_name 
        FROM users u 
        LEFT JOIN user_profiles p ON u.id = p.user_id 
        WHERE u.id = ?
    ");
    $user_stmt->execute([$user_id]);
    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'User not found']);
        return;
    }
    
    // Get transactions
    $trans_stmt = $pdo->prepare("
        SELECT 
            t.*,
            ta.action_name,
            b.group_id,
            ug.name as group_name,
            ug.color as group_color
        FROM token_transactions t
        LEFT JOIN token_actions ta ON t.action_id = ta.id
        LEFT JOIN budgets b ON t.budget_id = b.id
        LEFT JOIN user_groups ug ON b.group_id = ug.id
        WHERE t.user_id = ?
        ORDER BY t.created_at DESC
        LIMIT 100
    ");
    $trans_stmt->execute([$user_id]);
    $transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $html = generateUserTransactionsHTML($user, $transactions);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateUserTransactionsHTML($user, $transactions) {
    $display_name = $user['full_name'] ?: $user['username'];
    
    $html = "
    <div class='mb-4'>
        <h6>Transactions for {$display_name}</h6>
        <p class='text-muted'>@{$user['username']} • " . count($transactions) . " transactions</p>
    </div>
    
    <div class='table-responsive'>
        <table class='table table-hover'>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Action</th>
                    <th>Amount</th>
                    <th>Type</th>
                    <th>Group</th>
                    <th>Balance After</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>";
    
    if (empty($transactions)) {
        $html .= "<tr><td colspan='7' class='text-center text-muted'>No transactions found</td></tr>";
    } else {
        foreach ($transactions as $trans) {
            $amount_class = $trans['transaction_type'] == 'credit' ? 'text-success' : 'text-danger';
            $amount_sign = $trans['transaction_type'] == 'credit' ? '+' : '-';
            $type_color = [
                'credit' => 'success',
                'debit' => 'danger',
                'purchase' => 'warning',
                'refund' => 'info'
            ][$trans['transaction_type']] ?? 'secondary';
            
            $html .= "
                <tr>
                    <td>" . date('M j, Y H:i', strtotime($trans['created_at'])) . "</td>
                    <td>" . ($trans['action_name'] ?: 'Manual Transaction') . "</td>
                    <td class='{$amount_class}'>{$amount_sign}" . number_format($trans['amount'], 2) . "</td>
                    <td><span class='badge bg-{$type_color}'>" . ucfirst($trans['transaction_type']) . "</span></td>
                    <td>";
            
            if ($trans['group_name']) {
                $html .= "<div class='d-flex align-items-center'>
                            <div class='color-box me-1' style='width: 8px; height: 8px; background-color: {$trans['group_color']}; border-radius: 2px;'></div>
                            {$trans['group_name']}
                          </div>";
            } else {
                $html .= "<span class='text-muted'>Personal</span>";
            }
            
            $html .= "
                    </td>
                    <td>" . number_format($trans['balance_after'], 2) . "</td>
                    <td>" . ($trans['description'] ?: '-') . "</td>
                </tr>";
        }
    }
    
    $html .= "
            </tbody>
        </table>
    </div>";
    
    return $html;
}

function handleGetUserBudget() {
    global $pdo;
    
    $user_id = $_GET['user_id'] ?? 0;
    
    // Get user info
    $user_stmt = $pdo->prepare("
        SELECT u.*, p.full_name 
        FROM users u 
        LEFT JOIN user_profiles p ON u.id = p.user_id 
        WHERE u.id = ?
    ");
    $user_stmt->execute([$user_id]);
    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'User not found']);
        return;
    }
    
    // Get user's budget access through groups
    $budgets_stmt = $pdo->prepare("
        SELECT DISTINCT
            b.*,
            ug.name as group_name,
            ug.color as group_color,
            ugm.role_in_group
        FROM budgets b
        INNER JOIN user_groups ug ON b.group_id = ug.id
        INNER JOIN user_group_memberships ugm ON ug.id = ugm.group_id
        WHERE ugm.user_id = ? AND b.is_active = 1 AND ug.is_active = 1
        ORDER BY b.created_at DESC
    ");
    $budgets_stmt->execute([$user_id]);
    $budgets = $budgets_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get user's transaction summary
    $trans_summary_stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_transactions,
            SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) as total_credits,
            SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) as total_debits,
            MAX(created_at) as last_transaction
        FROM token_transactions 
        WHERE user_id = ?
    ");
    $trans_summary_stmt->execute([$user_id]);
    $trans_summary = $trans_summary_stmt->fetch(PDO::FETCH_ASSOC);
    
    $html = generateUserBudgetHTML($user, $budgets, $trans_summary);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateUserBudgetHTML($user, $budgets, $trans_summary) {
    $display_name = $user['full_name'] ?: $user['username'];
    
    $html = "
    <div class='mb-4'>
        <h6>Budget Access for {$display_name}</h6>
        <p class='text-muted'>@{$user['username']} • " . count($budgets) . " accessible budgets</p>
    </div>
    
    <div class='row mb-4'>
        <div class='col-md-3'>
            <div class='card border-0 bg-light text-center'>
                <div class='card-body'>
                    <h5 class='text-primary'>{$trans_summary['total_transactions']}</h5>
                    <small class='text-muted'>Total Transactions</small>
                </div>
            </div>
        </div>
        <div class='col-md-3'>
            <div class='card border-0 bg-light text-center'>
                <div class='card-body'>
                    <h5 class='text-success'>" . number_format($trans_summary['total_credits'], 2) . "</h5>
                    <small class='text-muted'>Total Credits</small>
                </div>
            </div>
        </div>
        <div class='col-md-3'>
            <div class='card border-0 bg-light text-center'>
                <div class='card-body'>
                    <h5 class='text-danger'>" . number_format($trans_summary['total_debits'], 2) . "</h5>
                    <small class='text-muted'>Total Debits</small>
                </div>
            </div>
        </div>
        <div class='col-md-3'>
            <div class='card border-0 bg-light text-center'>
                <div class='card-body'>
                    <h6 class='text-info'>" . ($trans_summary['last_transaction'] ? date('M j', strtotime($trans_summary['last_transaction'])) : 'Never') . "</h6>
                    <small class='text-muted'>Last Transaction</small>
                </div>
            </div>
        </div>
    </div>
    
    <h6>Accessible Budgets</h6>
    <div class='table-responsive'>
        <table class='table table-hover'>
            <thead>
                <tr>
                    <th>Group</th>
                    <th>Role</th>
                    <th>Balance</th>
                    <th>Total Spent</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>";
    
    if (empty($budgets)) {
        $html .= "<tr><td colspan='5' class='text-center text-muted'>No budget access found</td></tr>";
    } else {
        foreach ($budgets as $budget) {
            $balance_color = $budget['balance'] > 50 ? 'success' : ($budget['balance'] > 10 ? 'warning' : 'danger');
            $role_color = [
                'owner' => 'danger',
                'manager' => 'warning', 
                'member' => 'primary'
            ][$budget['role_in_group']] ?? 'secondary';
            
            $html .= "
                <tr>
                    <td>
                        <div class='d-flex align-items-center'>
                            <div class='color-box me-2' style='width: 12px; height: 12px; background-color: {$budget['group_color']}; border-radius: 2px;'></div>
                            {$budget['group_name']}
                        </div>
                    </td>
                    <td><span class='badge bg-{$role_color}'>" . ucfirst($budget['role_in_group']) . "</span></td>
                    <td><span class='badge bg-{$balance_color}'>" . number_format($budget['balance'], 2) . " tokens</span></td>
                    <td>" . number_format($budget['total_spent'], 2) . " tokens</td>
                    <td>
                        <button class='btn btn-outline-primary btn-sm' onclick='viewBudgetTransactions({$budget['id']})'>
                            <i class='fas fa-eye me-1'></i>View Transactions
                        </button>
                    </td>
                </tr>";
        }
    }
    
    $html .= "
            </tbody>
        </table>
    </div>
    
    <div class='text-center mt-3'>
        <button class='btn btn-primary' onclick='viewUserTransactions({$user['id']})'>
            <i class='fas fa-list me-1'></i>View All Transactions
        </button>
    </div>";
    
    return $html;
}

function handleGetBudgetTransactions() {
    global $pdo;
    
    $budget_id = $_GET['budget_id'] ?? 0;
    
    // Get budget info
    $budget_stmt = $pdo->prepare("
        SELECT 
            b.*,
            ug.name as group_name,
            ug.color as group_color
        FROM budgets b
        LEFT JOIN user_groups ug ON b.group_id = ug.id
        WHERE b.id = ?
    ");
    $budget_stmt->execute([$budget_id]);
    $budget = $budget_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$budget) {
        echo json_encode(['success' => false, 'message' => 'Budget not found']);
        return;
    }
    
    // Get transactions
    $trans_stmt = $pdo->prepare("
        SELECT 
            t.*,
            u.username,
            p.full_name,
            ta.action_name
        FROM token_transactions t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN token_actions ta ON t.action_id = ta.id
        WHERE t.budget_id = ?
        ORDER BY t.created_at DESC
    ");
    $trans_stmt->execute([$budget_id]);
    $transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $html = generateBudgetTransactionsHTML($budget, $transactions);
    echo json_encode(['success' => true, 'html' => $html]);
}

function generateBudgetTransactionsHTML($budget, $transactions) {
    $html = "
    <div class='mb-4'>
        <div class='d-flex align-items-center mb-2'>
            <div class='color-box me-2' style='width: 16px; height: 16px; background-color: {$budget['group_color']}; border-radius: 3px;'></div>
            <h6 class='mb-0'>{$budget['group_name']} Budget</h6>
        </div>
        <div class='row g-3 mb-3'>
            <div class='col-md-3'>
                <div class='card border-0 bg-light text-center'>
                    <div class='card-body py-2'>
                        <h6 class='text-success mb-0'>" . number_format($budget['balance'], 2) . "</h6>
                        <small class='text-muted'>Current Balance</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card border-0 bg-light text-center'>
                    <div class='card-body py-2'>
                        <h6 class='text-info mb-0'>" . number_format($budget['total_purchased'], 2) . "</h6>
                        <small class='text-muted'>Total Purchased</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card border-0 bg-light text-center'>
                    <div class='card-body py-2'>
                        <h6 class='text-danger mb-0'>" . number_format($budget['total_spent'], 2) . "</h6>
                        <small class='text-muted'>Total Spent</small>
                    </div>
                </div>
            </div>
            <div class='col-md-3'>
                <div class='card border-0 bg-light text-center'>
                    <div class='card-body py-2'>
                        <h6 class='text-primary mb-0'>" . count($transactions) . "</h6>
                        <small class='text-muted'>Total Transactions</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class='table-responsive'>
        <table class='table table-hover'>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>User</th>
                    <th>Action</th>
                    <th>Amount</th>
                    <th>Type</th>
                    <th>Balance Before</th>
                    <th>Balance After</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>";
    
    if (empty($transactions)) {
        $html .= "<tr><td colspan='8' class='text-center text-muted'>No transactions found</td></tr>";
    } else {
        foreach ($transactions as $trans) {
            $user_name = $trans['full_name'] ?: $trans['username'];
            $amount_class = $trans['transaction_type'] == 'credit' ? 'text-success' : 'text-danger';
            $amount_sign = $trans['transaction_type'] == 'credit' ? '+' : '-';
            $type_color = [
                'credit' => 'success',
                'debit' => 'danger',
                'purchase' => 'warning',
                'refund' => 'info'
            ][$trans['transaction_type']] ?? 'secondary';
            
            $html .= "
                <tr>
                    <td>" . date('M j, Y H:i', strtotime($trans['created_at'])) . "</td>
                    <td>
                        <strong>{$user_name}</strong>
                        <br><small class='text-muted'>@{$trans['username']}</small>
                    </td>
                    <td>" . ($trans['action_name'] ?: 'Manual Transaction') . "</td>
                    <td class='{$amount_class}'>{$amount_sign}" . number_format($trans['amount'], 2) . "</td>
                    <td><span class='badge bg-{$type_color}'>" . ucfirst($trans['transaction_type']) . "</span></td>
                    <td>" . number_format($trans['balance_before'], 2) . "</td>
                    <td>" . number_format($trans['balance_after'], 2) . "</td>
                    <td>" . ($trans['description'] ?: '-') . "</td>
                </tr>";
        }
    }
    
    $html .= "
            </tbody>
        </table>
    </div>";
    
    return $html;
}

function handleCreateBudget() {
    global $pdo;
    
    $group_id = $_POST['group_id'] ?? 0;
    $amount = floatval($_POST['amount'] ?? 0);
    $currency = $_POST['currency'] ?? 'USD';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $created_by = $_SESSION['user_id'];
    
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Amount must be greater than 0']);
        return;
    }
    
    // Check if group exists and doesn't already have a budget
    $check_stmt = $pdo->prepare("
        SELECT g.id, b.id as budget_id 
        FROM user_groups g
        LEFT JOIN budgets b ON g.id = b.group_id AND b.is_active = 1
        WHERE g.id = ? AND g.is_active = 1
    ");
    $check_stmt->execute([$group_id]);
    $result = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$result) {
        echo json_encode(['success' => false, 'message' => 'Group not found']);
        return;
    }
    
    if ($result['budget_id']) {
        echo json_encode(['success' => false, 'message' => 'Group already has an active budget']);
        return;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Create budget
        $budget_stmt = $pdo->prepare("
            INSERT INTO budgets (group_id, balance, total_purchased, total_spent, currency, is_active, created_by, created_at, updated_at)
            VALUES (?, ?, ?, 0, ?, ?, ?, NOW(), NOW())
        ");
        $budget_stmt->execute([$group_id, $amount, $amount, $currency, $is_active, $created_by]);
        
        $budget_id = $pdo->lastInsertId();
        
        // Create initial transaction record
        $trans_stmt = $pdo->prepare("
            INSERT INTO token_transactions (budget_id, user_id, transaction_type, amount, balance_before, balance_after, description, created_by, created_at)
            VALUES (?, ?, 'credit', ?, 0, ?, 'Initial budget allocation', ?, NOW())
        ");
        $trans_stmt->execute([$budget_id, $created_by, $amount, $amount, $created_by]);
        
        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Budget created successfully']);
        
    } catch (Exception $e) {
        $pdo->rollback();
        echo json_encode(['success' => false, 'message' => 'Error creating budget: ' . $e->getMessage()]);
    }
}

function handleAddGroupMember() {
    global $pdo;
    
    $group_id = $_POST['group_id'] ?? 0;
    $user_id = $_POST['user_id'] ?? 0;
    $role = $_POST['role'] ?? 'member';
    $added_by = $_SESSION['user_id'];
    
    // Validate role
    if (!in_array($role, ['member', 'manager', 'owner'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid role']);
        return;
    }
    
    // Check if user is already a member
    $check_stmt = $pdo->prepare("SELECT id FROM user_group_memberships WHERE group_id = ? AND user_id = ?");
    $check_stmt->execute([$group_id, $user_id]);
    
    if ($check_stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'User is already a member of this group']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO user_group_memberships (group_id, user_id, role_in_group, added_by, joined_at, created_at)
            VALUES (?, ?, ?, ?, NOW(), NOW())
        ");
        $stmt->execute([$group_id, $user_id, $role, $added_by]);
        
        echo json_encode(['success' => true, 'message' => 'Member added successfully']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error adding member: ' . $e->getMessage()]);
    }
}

function handleRemoveGroupMember() {
    global $pdo;
    
    $group_id = $_POST['group_id'] ?? 0;
    $user_id = $_POST['user_id'] ?? 0;
    
    try {
        $stmt = $pdo->prepare("DELETE FROM user_group_memberships WHERE group_id = ? AND user_id = ?");
        $stmt->execute([$group_id, $user_id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Member removed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Member not found']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error removing member: ' . $e->getMessage()]);
    }
}

function handleUpdateMemberRole() {
    global $pdo;
    
    $group_id = $_POST['group_id'] ?? 0;
    $user_id = $_POST['user_id'] ?? 0;
    $role = $_POST['role'] ?? 'member';
    
    // Validate role
    if (!in_array($role, ['member', 'manager', 'owner'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid role']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            UPDATE user_group_memberships 
            SET role_in_group = ? 
            WHERE group_id = ? AND user_id = ?
        ");
        $stmt->execute([$role, $group_id, $user_id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Role updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Member not found']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error updating role: ' . $e->getMessage()]);
    }
}
?>
