<?php
/**
 * HuSNS - 管理员管理后台页面
 */
?>
<div class="admin-content">
    <div class="admin-header">
        <h1>管理员管理</h1>
    </div>
    
    <!-- 管理员列表 -->
    <div class="admin-table">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>用户信息</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>注册时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                <tr>
                    <td>
                        <img src="<?php echo $user['avatar'] ? $this->uploadUrl($user['avatar']) : $this->assetUrl('images/default-avatar.png'); ?>" 
                             alt="" class="avatar-md">
                        <div class="user-info">
                            <span class="username"><?php echo htmlspecialchars($user['username']); ?></span>
                            <?php if ($user['id'] == 1): ?>
                            <span class="badge badge-primary">超级管理员</span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                    <td>
                        <div class="role-list">
                            <?php foreach ($user['roles'] as $role): ?>
                            <span class="badge badge-info" style="margin-right: 5px;">
                                <?php echo htmlspecialchars($role['name']); ?>
                            </span>
                            <?php endforeach; ?>
                            <?php if (empty($user['roles']) && $user['id'] != 1): ?>
                            <span class="text-muted">未分配角色</span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><?php echo date('Y-m-d H:i', $user['created_at']); ?></td>
                    <td>
                        <button class="btn btn-sm btn-default" onclick="manageRoles(<?php echo $user['id']; ?>)">
                            <i class="fa fa-user-circle"></i> 管理角色
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if (empty($users)): ?>
        <div class="empty-state">
            <i class="fa fa-users"></i>
            <p>暂无管理员数据</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 角色管理弹窗 -->
<div class="modal fade" id="roleModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">管理角色</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="userId">
                
                <div class="form-group">
                    <label>可用角色</label>
                    <div id="roleList">
                        <?php foreach ($roles as $role): ?>
                        <label class="role-checkbox">
                            <input type="checkbox" data-role-id="<?php echo $role['id']; ?>">
                            <?php echo htmlspecialchars($role['name']); ?>
                            <span class="role-desc"><?php echo htmlspecialchars($role['description']); ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveRoles()">保存</button>
            </div>
        </div>
    </div>
</div>

<script>
function manageRoles(userId) {
    $('#userId').val(userId);
    
    // 清除所有选中状态
    $('#roleList input[type="checkbox"]').prop('checked', false);
    
    // 获取用户当前角色并设置选中状态
    $.get('<?php echo Helper::url('admin/admin_users/get_roles'); ?>?user_id=' + userId, function(res) {
        if (res.success) {
            res.data.forEach(function(roleId) {
                $('#roleList input[data-role-id="' + roleId + '"]').prop('checked', true);
            });
        }
    }, 'json');
    
    $('#roleModal').modal('show');
}

function saveRoles() {
    var userId = $('#userId').val();
    var selectedRoles = [];
    
    $('#roleList input[type="checkbox"]:checked').each(function() {
        selectedRoles.push($(this).data('role-id'));
    });
    
    // 先获取当前角色
    $.get('<?php echo Helper::url('admin/admin_users/get_roles'); ?>?user_id=' + userId, function(currentRoles) {
        var promises = [];
        
        // 取消已选中但现在未选中的角色
        if (currentRoles.success) {
            currentRoles.data.forEach(function(roleId) {
                if (selectedRoles.indexOf(roleId) === -1) {
                    promises.push(revokeRole(userId, roleId));
                }
            });
        }
        
        // 分配新选中的角色
        selectedRoles.forEach(function(roleId) {
            if (!currentRoles.success || currentRoles.data.indexOf(roleId) === -1) {
                promises.push(assignRole(userId, roleId));
            }
        });
        
        Promise.all(promises).then(function() {
            alert('角色更新成功');
            $('#roleModal').modal('hide');
            window.location.reload();
        }).catch(function() {
            alert('更新失败');
        });
    }, 'json');
}

function assignRole(userId, roleId) {
    return new Promise(function(resolve) {
        $.post('<?php echo Helper::url('admin/admin_users/assign_role'); ?>', {
            user_id: userId,
            role_id: roleId,
            csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
        }, function(res) {
            resolve(res);
        }, 'json');
    });
}

function revokeRole(userId, roleId) {
    return new Promise(function(resolve) {
        $.post('<?php echo Helper::url('admin/admin_users/revoke_role'); ?>', {
            user_id: userId,
            role_id: roleId,
            csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
        }, function(res) {
            resolve(res);
        }, 'json');
    });
}

// 添加获取用户角色方法
</script>
