<?php
requireAdmin();

$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 20;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// 构建查询条件
$where = "role = 'user'";
if ($search) {
    $search = $db->escape($search);
    $where .= " AND (username LIKE '%$search%' OR email LIKE '%$search%')";
}

// 获取总数
$total_result = $db->query("SELECT COUNT(*) as cnt FROM users WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

// 获取用户列表
$users = $db->fetchAll("
    SELECT u.*, ug.name as group_name 
    FROM users u 
    LEFT JOIN user_groups ug ON u.group_id = ug.id 
    WHERE $where 
    ORDER BY u.id DESC 
    LIMIT $offset, $perpage
");

// 处理用户状态切换
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'toggle_status') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->query("UPDATE users SET status = $status WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}

// 处理删除
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    // 检查是否有订单或授权码关联
    $orders = $db->fetchOne("SELECT id FROM orders WHERE user_id = $id LIMIT 1");
    $licenses = $db->fetchOne("SELECT id FROM licenses WHERE user_id = $id LIMIT 1");
    if ($orders || $licenses) {
        $error = '该用户存在订单或授权记录，无法删除';
    } else {
        $db->query("DELETE FROM users WHERE id = $id AND role = 'user'");
        redirect('?page=users');
    }
}
?>

<div class="users-manager">
    <div class="page-header">
        <h2>用户管理</h2>
    </div>
    
    <?php if (isset($error)): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="users">
            <input type="text" name="search" placeholder="搜索用户名/邮箱" value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-primary">搜索</button>
            <?php if ($search): ?>
                <a href="?page=users" class="btn btn-secondary">清空</a>
            <?php endif; ?>
        </form>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>余额</th>
                    <th>会员等级</th>
                    <th>状态</th>
                    <th>注册时间</th>
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($users)): ?>
                    <tr><td colspan="8" style="text-align: center;">暂无用户</td></tr>
                <?php else: ?>
                    <?php foreach ($users as $u): ?>
                        <tr>
                            <td><?php echo $u['id']; ?></td>
                            <td><strong><?php echo htmlspecialchars($u['username']); ?></strong></td>
                            <td><?php echo htmlspecialchars($u['email']); ?></td>
                            <td>¥<?php echo number_format($u['balance'], 2); ?></td>
                            <td><?php echo htmlspecialchars($u['group_name'] ?? '普通会员'); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $u['status'] ? 'active' : 'inactive'; ?>">
                                    <?php echo $u['status'] ? '正常' : '禁用'; ?>
                                </span>
                            </td>
                            <td><?php echo $u['created_at']; ?></td>
                            <td>
                                <button class="btn-icon" onclick="toggleStatus(<?php echo $u['id']; ?>, <?php echo $u['status'] ? 0 : 1; ?>)" title="切换状态">🔄</button>
                                <a href="?page=users&delete=<?php echo $u['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此用户吗？')" title="删除">🗑️</a>
                                <a href="?page=user_detail&id=<?php echo $u['id']; ?>" class="btn-icon" title="查看详情">👁️</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php
            $total_pages = ceil($total / $perpage);
            for ($i = 1; $i <= $total_pages; $i++):
            ?>
                <a href="?page=users&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.search-bar {
    margin-bottom: 20px;
}
.search-bar form {
    display: flex;
    gap: 10px;
}
.search-bar input {
    flex: 1;
    padding: 10px 16px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    background: var(--bg-primary);
}
.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
    padding: 4px 8px;
    border-radius: 4px;
}
.btn-icon:hover {
    background: var(--bg-secondary);
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 20px;
}
.page-link {
    padding: 6px 12px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
</style>

<script>
function toggleStatus(id, status) {
    fetch('?page=users&action=toggle_status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${id}&status=${status}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.showToast('状态更新成功', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast(data.message || '操作失败', 'error');
        }
    });
}
</script>