<?php
/**
 * 用户管理
 */
require_once __DIR__ . '/../includes/functions.php';

// 检查是否登录且是管理员
if (!isLoggedIn() || !isAdmin()) {
    setFlashMessage('error', '您没有权限访问此页面');
    redirect(SITE_URL . '/index.php');
}

$action = $_GET['action'] ?? 'list';
$currentUser = getCurrentUser();

// 设置/取消管理员
if ($action === 'set_admin' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $role = intval($_GET['role'] ?? 0);
    
    // 获取目标用户信息
    $targetUser = db()->queryOne("SELECT * FROM users WHERE id = ?", [$id]);
    
    if (!$targetUser) {
        setFlashMessage('error', '用户不存在');
    } elseif ($id == $currentUser['id']) {
        // 不能修改自己的权限
        setFlashMessage('error', '不能修改自己的权限');
    } elseif ($targetUser['role'] == 2) {
        // 不能修改超级管理员权限
        setFlashMessage('error', '超级管理员权限不可修改');
    } elseif ($role == 2 && $currentUser['role'] != 2) {
        // 只有超级管理员能设置超级管理员
        setFlashMessage('error', '只有超级管理员能设置超级管理员');
    } else {
        db()->execute("UPDATE users SET role = ? WHERE id = ?", [$role, $id]);
        $roleName = $role == 2 ? '超级管理员' : ($role == 1 ? '管理员' : '普通用户');
        setFlashMessage('success', '已设为' . $roleName);
    }
    redirect(SITE_URL . '/admin/users.php');
}

// 禁用/启用用户
if ($action === 'set_status' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $status = intval($_GET['status'] ?? 1);
    
    // 获取目标用户信息
    $targetUser = db()->queryOne("SELECT * FROM users WHERE id = ?", [$id]);
    
    if (!$targetUser) {
        setFlashMessage('error', '用户不存在');
    } elseif ($id == $currentUser['id']) {
        // 不能禁用自己
        setFlashMessage('error', '不能禁用自己的账号');
    } elseif ($targetUser['role'] == 2) {
        // 不能禁用超级管理员
        setFlashMessage('error', '超级管理员账号不可禁用');
    } else {
        db()->execute("UPDATE users SET status = ? WHERE id = ?", [$status, $id]);
        setFlashMessage('success', $status ? '用户已启用' : '用户已禁用');
    }
    redirect(SITE_URL . '/admin/users.php');
}

// 删除用户
if ($action === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    // 获取目标用户信息
    $targetUser = db()->queryOne("SELECT * FROM users WHERE id = ?", [$id]);
    
    if (!$targetUser) {
        setFlashMessage('error', '用户不存在');
    } elseif ($id == $currentUser['id']) {
        // 不能删除自己
        setFlashMessage('error', '不能删除自己的账号');
    } elseif ($targetUser['role'] == 2) {
        // 不能删除超级管理员
        setFlashMessage('error', '超级管理员账号不可删除');
    } else {
        // 软删除：将用户状态设为0，并标记为已删除
        db()->execute("UPDATE users SET status = 0, username = CONCAT(username, '_deleted_', id) WHERE id = ?", [$id]);
        setFlashMessage('success', '用户已删除');
    }
    redirect(SITE_URL . '/admin/users.php');
}

$pageTitle = '用户管理';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <?php if ($action === 'list'): ?>
        <!-- 正常用户列表 -->
        <?php
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        if ($search) {
            $isIdSearch = is_numeric($search);
            
            if ($isIdSearch) {
                $users = db()->query(
                    "SELECT * FROM users WHERE status != 0 AND id = ? 
                     ORDER BY role DESC, created_at DESC LIMIT ? OFFSET ?",
                    [$search, $perPage, $offset]
                );
                $totalResult = db()->queryOne(
                    "SELECT COUNT(*) as total FROM users WHERE status != 0 AND id = ?",
                    [$search]
                );
            } else {
                $users = db()->query(
                    "SELECT * FROM users WHERE status != 0 AND (username LIKE ? OR email LIKE ?) 
                     ORDER BY role DESC, created_at DESC LIMIT ? OFFSET ?",
                    ["%$search%", "%$search%", $perPage, $offset]
                );
                $totalResult = db()->queryOne(
                    "SELECT COUNT(*) as total FROM users WHERE status != 0 AND (username LIKE ? OR email LIKE ?)",
                    ["%$search%", "%$search%"]
                );
            }
        } else {
            $users = db()->query(
                "SELECT * FROM users WHERE status != 0 ORDER BY role DESC, created_at DESC LIMIT ? OFFSET ?",
                [$perPage, $offset]
            );
            $totalResult = db()->queryOne("SELECT COUNT(*) as total FROM users WHERE status != 0");
        }
        
        $total = $totalResult['total'];
        
        // 获取禁用用户数量
        $bannedCount = db()->queryOne("SELECT COUNT(*) as count FROM users WHERE status = 0")['count'] ?? 0;
        ?>
        
        <!-- 头部区域 - 蓝白色主题 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; padding: 20px 24px; background: #ffffff; color: #1e293b; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
            <h1 style="margin: 0; font-size: 22px; font-weight: 600;"><i class="fas fa-users" style="color: #2563eb; margin-right: 8px;"></i>用户管理</h1>
            <div style="display: flex; gap: 16px; align-items: center;">
                <a href="?action=banned" style="background: #fef2f2; color: #dc2626; padding: 8px 16px; border-radius: 8px; text-decoration: none; font-size: 14px; border: 1px solid #fecaca;">
                    <i class="fas fa-ban"></i> 禁用用户 (<?php echo $bannedCount; ?>)
                </a>
                <span style="color: #64748b; font-size: 14px;">共 <?php echo $total; ?> 位正常用户</span>
            </div>
        </div>
        
        <!-- 搜索区域 -->
        <div class="card" style="margin-bottom: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); background: white;">
            <div class="card-body" style="padding: 20px;">
                <form method="GET" action="" style="display: flex; gap: 12px;">
                    <input type="text" name="search" class="form-control" placeholder="搜索用户ID、用户名或邮箱" value="<?php echo e($search); ?>" style="flex: 1; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px;">
                    <button type="submit" class="btn" style="background: #2563eb; color: white; padding: 12px 24px; border-radius: 8px; border: none; cursor: pointer; font-weight: 500;"><i class="fas fa-search"></i> 搜索</button>
                    <?php if ($search): ?>
                        <a href="users.php" class="btn" style="background: #f8f9fa; color: #666; padding: 12px 24px; border-radius: 8px; border: 1px solid #ddd; text-decoration: none;">清除</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <!-- 用户列表 -->
        <div class="table-responsive" style="background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">ID</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">用户</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">邮箱</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">角色</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">发帖</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">回复</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">勋章</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">注册时间</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <?php
                    $medalCount = db()->queryOne("SELECT COUNT(*) as count FROM user_medals WHERE user_id = ?", [$user['id']]);
                    $medalNum = $medalCount['count'] ?? 0;
                    ?>
                    <tr style="border-bottom: 1px solid #f0f0f0;">
                        <td style="padding: 16px; color: #666;"><?php echo $user['id']; ?></td>
                        <td style="padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                    <?php if ($user['avatar']): ?>
                                        <img src="<?php echo SITE_URL . '/' . e($user['avatar']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover;">
                                    <?php else: ?>
                                        <i class="fas fa-user" style="color: #999;"></i>
                                    <?php endif; ?>
                                </div>
                                <span style="font-weight: 500; color: #333;"><?php echo e($user['username']); ?></span>
                            </div>
                        </td>
                        <td style="padding: 16px; color: #666; font-size: 14px;"><?php echo e($user['email']); ?></td>
                        <td style="padding: 16px; text-align: center;">
                            <?php if ($user['role'] == 2): ?>
                                <span style="background: #dc2626; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500;">超级管理员</span>
                            <?php elseif ($user['role'] == 1): ?>
                                <span style="background: #2563eb; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500;">管理员</span>
                            <?php else: ?>
                                <span style="background: #e0e0e0; color: #666; padding: 4px 12px; border-radius: 20px; font-size: 12px;">普通用户</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['post_count']; ?></td>
                        <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['reply_count']; ?></td>
                        <td style="padding: 16px; text-align: center;">
                            <a href="medals.php?action=user_medals&user_id=<?php echo $user['id']; ?>" style="text-decoration: none;">
                                <span style="font-weight: 600; color: <?php echo $medalNum > 0 ? '#2563eb' : '#999'; ?>; background: <?php echo $medalNum > 0 ? '#dbeafe' : '#f0f0f0'; ?>; padding: 6px 14px; border-radius: 20px; font-size: 13px;">
                                    <?php echo $medalNum; ?> 个
                                </span>
                            </a>
                        </td>
                        <td style="padding: 16px; text-align: center; color: #999; font-size: 13px;"><?php echo formatTime($user['created_at']); ?></td>
                        <td style="padding: 16px; text-align: center;">
                            <div style="display: flex; gap: 6px; justify-content: center; flex-wrap: wrap;">
                                <a href="../user.php?id=<?php echo $user['id']; ?>" target="_blank" style="background: #eff6ff; color: #2563eb; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #bfdbfe;">查看</a>
                                
                                <?php if ($user['role'] != 2): ?>
                                    <?php if ($user['role'] == 1): ?>
                                        <a href="?action=set_admin&id=<?php echo $user['id']; ?>&role=0" style="background: #fef2f2; color: #dc2626; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #fecaca;">取消管理</a>
                                    <?php else: ?>
                                        <a href="?action=set_admin&id=<?php echo $user['id']; ?>&role=1" style="background: #f0fdf4; color: #16a34a; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #86efac;">设管理员</a>
                                    <?php endif; ?>
                                    
                                    <a href="?action=set_status&id=<?php echo $user['id']; ?>&status=0" style="background: #fffbeb; color: #d97706; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #fcd34d;" onclick="return confirm('确定要禁用此用户吗？')">禁用</a>
                                    
                                    <a href="?action=delete&id=<?php echo $user['id']; ?>" style="background: #fef2f2; color: #dc2626; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #fecaca;" onclick="return confirm('确定要删除此用户吗？')">删除</a>
                                <?php else: ?>
                                    <span style="color: #999; font-size: 12px; padding: 6px 12px;">不可操作</span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total > $perPage): ?>
            <div style="margin-top: 24px;">
                <?php echo pagination($total, $page, $perPage, 'users.php?search=' . urlencode($search) . '&'); ?>
            </div>
        <?php endif; ?>
        
    <?php elseif ($action === 'banned'): ?>
        <!-- 禁用用户列表 -->
        <?php
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        $bannedUsers = db()->query(
            "SELECT * FROM users WHERE status = 0 ORDER BY created_at DESC LIMIT ? OFFSET ?",
            [$perPage, $offset]
        );
        
        $totalResult = db()->queryOne("SELECT COUNT(*) as total FROM users WHERE status = 0");
        $total = $totalResult['total'] ?? 0;
        ?>
        
        <!-- 头部区域 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; padding: 20px 24px; background: #fef2f2; color: #991b1b; border-radius: 12px; border: 1px solid #fecaca;">
            <h1 style="margin: 0; font-size: 22px; font-weight: 600;"><i class="fas fa-ban" style="margin-right: 8px;"></i>禁用用户列表</h1>
            <div style="display: flex; gap: 16px; align-items: center;">
                <a href="users.php" style="background: white; color: #2563eb; padding: 8px 16px; border-radius: 8px; text-decoration: none; font-size: 14px; border: 1px solid #bfdbfe;">
                    <i class="fas fa-arrow-left"></i> 返回正常用户
                </a>
                <span style="color: #7f1d1d; font-size: 14px;">共 <?php echo $total; ?> 位禁用用户</span>
            </div>
        </div>
        
        <?php if (empty($bannedUsers)): ?>
            <div style="text-align: center; padding: 80px 40px; background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                <div style="width: 100px; height: 100px; margin: 0 auto 24px; background: #f0f9ff; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-check-circle" style="font-size: 48px; color: #22c55e;"></i>
                </div>
                <p style="font-size: 18px; color: #334155; margin-bottom: 8px;">暂无禁用用户</p>
                <p style="font-size: 14px; color: #94a3b8;">所有用户都处于正常状态</p>
            </div>
        <?php else: ?>
            <div class="table-responsive" style="background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden;">
                <table class="table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #fef2f2;">
                            <th style="padding: 16px; text-align: left; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">ID</th>
                            <th style="padding: 16px; text-align: left; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">用户</th>
                            <th style="padding: 16px; text-align: left; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">邮箱</th>
                            <th style="padding: 16px; text-align: center; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">角色</th>
                            <th style="padding: 16px; text-align: center; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">发帖</th>
                            <th style="padding: 16px; text-align: center; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">回复</th>
                            <th style="padding: 16px; text-align: center; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">注册时间</th>
                            <th style="padding: 16px; text-align: center; font-weight: 600; color: #7f1d1d; border-bottom: 1px solid #fecaca;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bannedUsers as $user): ?>
                        <tr style="border-bottom: 1px solid #f0f0f0; background: #fffafa;">
                            <td style="padding: 16px; color: #666;"><?php echo $user['id']; ?></td>
                            <td style="padding: 16px;">
                                <div style="display: flex; align-items: center; gap: 12px;">
                                    <div style="width: 40px; height: 40px; border-radius: 50%; background: #fee2e2; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                        <?php if ($user['avatar']): ?>
                                            <img src="<?php echo SITE_URL . '/' . e($user['avatar']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover; filter: grayscale(50%);">
                                        <?php else: ?>
                                            <i class="fas fa-user" style="color: #dc2626;"></i>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <span style="font-weight: 500; color: #333;"><?php echo e($user['username']); ?></span>
                                        <span style="background: #dc2626; color: white; padding: 2px 8px; border-radius: 10px; font-size: 11px; margin-left: 8px;">已禁用</span>
                                    </div>
                                </div>
                            </td>
                            <td style="padding: 16px; color: #666; font-size: 14px;"><?php echo e($user['email']); ?></td>
                            <td style="padding: 16px; text-align: center;">
                                <?php if ($user['role'] == 2): ?>
                                    <span style="background: #dc2626; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px;">超级管理员</span>
                                <?php elseif ($user['role'] == 1): ?>
                                    <span style="background: #2563eb; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px;">管理员</span>
                                <?php else: ?>
                                    <span style="background: #e0e0e0; color: #666; padding: 4px 12px; border-radius: 20px; font-size: 12px;">普通用户</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['post_count']; ?></td>
                            <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['reply_count']; ?></td>
                            <td style="padding: 16px; text-align: center; color: #999; font-size: 13px;"><?php echo formatTime($user['created_at']); ?></td>
                            <td style="padding: 16px; text-align: center;">
                                <div style="display: flex; gap: 6px; justify-content: center; flex-wrap: wrap;">
                                    <a href="?action=set_status&id=<?php echo $user['id']; ?>&status=1" style="background: #f0fdf4; color: #16a34a; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #86efac; font-weight: 500;" onclick="return confirm('确定要启用此用户吗？')">
                                        <i class="fas fa-check"></i> 启用用户
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if ($total > $perPage): ?>
                <div style="margin-top: 24px;">
                    <?php echo pagination($total, $page, $perPage, 'users.php?action=banned&'); ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/footer.php'; ?>
