<?php
requireAdmin();



// 处理删除
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');
        exit;
    }
}

// ========== 页面数据 ==========
$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
");

// 统计数据
$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM users WHERE role = 'user'")['cnt'],
    'active' => $db->fetchOne("SELECT COUNT(*) as cnt FROM users WHERE role = 'user' AND status = 1")['cnt'],
    'banned' => $db->fetchOne("SELECT COUNT(*) as cnt FROM users WHERE role = 'user' AND status = 0")['cnt'],
    'today' => $db->fetchOne("SELECT COUNT(*) as cnt FROM users WHERE role = 'user' AND DATE(created_at) = CURDATE()")['cnt'],
];
?>

<div class="users-manager">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            用户管理
        </h2>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:account-multiple.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总用户数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:account-check.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['active']; ?></span>
                <span class="stat-label">正常用户</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:account-cancel.svg?color=%23ef4444" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['banned']; ?></span>
                <span class="stat-label">禁用用户</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:account-plus.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['today']; ?></span>
                <span class="stat-label">今日新增</span>
            </div>
        </div>
    </div>
    
    <!-- 错误提示 -->
    <?php if (isset($error)): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="users">
            <div class="search-input-wrapper">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=%239ca3af" width="18" height="18" class="search-icon" alt="">
                <input type="text" name="search" placeholder="搜索用户名或邮箱..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <button type="submit" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=white" width="16" height="16" style="vertical-align: middle; margin-right: 4px;" alt="">
                搜索
            </button>
            <?php if ($search): ?>
                <a href="?page=users" class="btn btn-secondary">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="vertical-align: middle; margin-right: 4px;" alt="">
                    清空
                </a>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- 用户列表 -->
    <?php if (empty($users)): ?>
        <div class="empty-state">
            <img src="https://api.iconify.design/mdi:account-search.svg?color=%239ca3af" width="64" height="64" alt="">
            <p>暂无用户数据</p>
            <span><?php echo $search ? '没有找到匹配的用户' : '还没有注册用户'; ?></span>
        </div>
    <?php else: ?>
        <div class="users-grid">
            <?php foreach ($users as $u): ?>
                <div class="user-card <?php echo $u['status'] == 0 ? 'disabled' : ''; ?>">
                    <div class="user-card-header">
                        <div class="user-avatar">
                            <img src="https://api.iconify.design/mdi:account-circle.svg?color=%23667eea" width="48" height="48" alt="">
                        </div>
                        <div class="user-info">
                            <h3><?php echo htmlspecialchars($u['username']); ?></h3>
                            <span class="user-email"><?php echo htmlspecialchars($u['email']); ?></span>
                        </div>
                        <div class="user-status">
                            <span class="status-badge status-<?php echo $u['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $u['id']; ?>">
                                <span class="status-dot"></span>
                                <?php echo $u['status'] ? '正常' : '禁用'; ?>
                            </span>
                        </div>
                    </div>
                    <div class="user-card-body">
                        <div class="user-meta">
                            <div class="meta-row">
                                <span class="meta-label">
                                    <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="16" height="16" alt="">
                                    余额
                                </span>
                                <span class="meta-value">¥<?php echo number_format($u['balance'], 2); ?></span>
                            </div>
                            <div class="meta-row">
                                <span class="meta-label">
                                    <img src="https://api.iconify.design/mdi:shield-account.svg?color=%238b5cf6" width="16" height="16" alt="">
                                    会员等级
                                </span>
                                <span class="meta-value"><?php echo htmlspecialchars($u['group_name'] ?? '普通会员'); ?></span>
                            </div>
                            <div class="meta-row">
                                <span class="meta-label">
                                    <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="16" height="16" alt="">
                                    注册时间
                                </span>
                                <span class="meta-value"><?php echo date('Y-m-d H:i', strtotime($u['created_at'])); ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="user-card-footer">
                        <button class="action-btn toggle-status-btn" data-id="<?php echo $u['id']; ?>" data-status="<?php echo $u['status']; ?>" title="<?php echo $u['status'] ? '禁用用户' : '启用用户'; ?>">
                            <?php if ($u['status']): ?>
                                <img src="https://api.iconify.design/mdi:account-cancel.svg?color=%23ef4444" width="18" height="18" alt="">
                            <?php else: ?>
                                <img src="https://api.iconify.design/mdi:account-check.svg?color=%2310b981" width="18" height="18" alt="">
                            <?php endif; ?>
                        </button>
                        <a href="?page=user_detail&id=<?php echo $u['id']; ?>" class="action-btn" title="查看详情">
                            <img src="https://api.iconify.design/mdi:eye.svg?color=%23667eea" width="18" height="18" alt="">
                        </a>
                        <a href="?page=users&delete=<?php echo $u['id']; ?>" class="action-btn delete-btn" onclick="return confirm('确定删除此用户吗？删除后不可恢复。')" title="删除用户">
                            <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="18" height="18" alt="">
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=users&p=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=users&p=1&search=<?php echo urlencode($search); ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $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; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=users&p=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=users&p=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.users-manager {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.page-header h2 img {
    display: inline-block;
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: var(--radius-md);
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

/* 搜索栏 */
.search-bar {
    margin-bottom: 24px;
}
.search-bar form {
    display: flex;
    gap: 12px;
    align-items: center;
}
.search-input-wrapper {
    position: relative;
    flex: 1;
    max-width: 360px;
}
.search-input-wrapper .search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    pointer-events: none;
}
.search-input-wrapper input {
    width: 100%;
    padding: 12px 16px 12px 44px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    background: var(--bg-primary);
    font-size: 14px;
    transition: all 0.2s;
}
.search-input-wrapper input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 11px 24px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    gap: 6px;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}

/* 用户卡片网格 */
.users-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 20px;
}
.user-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    overflow: hidden;
    transition: all 0.2s;
    display: flex;
    flex-direction: column;
}
.user-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.user-card.disabled {
    opacity: 0.75;
}
.user-card-header {
    display: flex;
    align-items: flex-start;
    padding: 20px 20px 16px;
    border-bottom: 1px solid var(--border-color);
}
.user-avatar {
    margin-right: 12px;
}
.user-avatar img {
    display: block;
}
.user-info {
    flex: 1;
    min-width: 0;
}
.user-info h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 4px;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.user-email {
    font-size: 13px;
    color: var(--text-muted);
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.user-status {
    flex-shrink: 0;
}
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-active .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

/* 卡片内容 */
.user-card-body {
    padding: 16px 20px;
    flex: 1;
}
.user-meta {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.meta-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.meta-label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
}
.meta-value {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
}

/* 卡片操作 */
.user-card-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    padding: 12px 20px 20px;
    border-top: 1px solid var(--border-color);
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
}
.empty-state img {
    opacity: 0.5;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-secondary);
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 4px;
}
.empty-state span {
    color: var(--text-muted);
    font-size: 14px;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .users-grid {
        grid-template-columns: 1fr;
    }
    .search-bar form {
        flex-wrap: wrap;
    }
    .search-input-wrapper {
        max-width: 100%;
    }
}
</style>

<script>
// 绑定切换状态按钮事件
document.querySelectorAll('.toggle-status-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const btnId = this.getAttribute('data-id');
        const currentStatus = parseInt(this.getAttribute('data-status'));
        const newStatus = currentStatus === 1 ? 0 : 1;
        
        const btn = this;
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="loading-spinner"></span>';
        btn.disabled = true;
        
        const statusBadge = document.getElementById('status-badge-' + btnId);
        const userCard = btn.closest('.user-card');
        
        fetch('/api/admin_toggle_user_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${btnId}&status=${newStatus}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新状态徽章
                if (statusBadge) {
                    if (newStatus === 1) {
                        statusBadge.className = 'status-badge status-active';
                        statusBadge.innerHTML = '<span class="status-dot"></span>正常';
                    } else {
                        statusBadge.className = 'status-badge status-inactive';
                        statusBadge.innerHTML = '<span class="status-dot"></span>禁用';
                    }
                }
                
                // 更新卡片样式
                if (userCard) {
                    if (newStatus === 1) {
                        userCard.classList.remove('disabled');
                    } else {
                        userCard.classList.add('disabled');
                    }
                }
                
                // 更新按钮
                btn.setAttribute('data-status', newStatus);
                if (newStatus === 1) {
                    btn.innerHTML = '<img src="https://api.iconify.design/mdi:account-cancel.svg?color=%23ef4444" width="18" height="18" alt="">';
                    btn.setAttribute('title', '禁用用户');
                } else {
                    btn.innerHTML = '<img src="https://api.iconify.design/mdi:account-check.svg?color=%2310b981" width="18" height="18" alt="">';
                    btn.setAttribute('title', '启用用户');
                }
                btn.disabled = false;
                
                // 更新顶部统计卡片
                const statValues = document.querySelectorAll('.stat-card .stat-value');
                const activeStat = statValues[1]; // 正常用户是第二个卡片
                const bannedStat = statValues[2]; // 禁用用户是第三个卡片
                
                if (activeStat && bannedStat) {
                    let activeCount = parseInt(activeStat.innerText) || 0;
                    let bannedCount = parseInt(bannedStat.innerText) || 0;
                    
                    if (newStatus === 1) {
                        // 启用用户：正常+1，禁用-1
                        activeStat.innerText = activeCount + 1;
                        bannedStat.innerText = Math.max(0, bannedCount - 1);
                    } else {
                        // 禁用用户：正常-1，禁用+1
                        activeStat.innerText = Math.max(0, activeCount - 1);
                        bannedStat.innerText = bannedCount + 1;
                    }
                }
                
                window.showToast && window.showToast('状态更新成功', 'success');
            } else {
                window.showToast && window.showToast(data.message || '操作失败', 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast && window.showToast('网络错误', 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    });
});

// 加载动画样式
const style = document.createElement('style');
style.textContent = `
    .loading-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(102, 126, 234, 0.3);
        border-radius: 50%;
        border-top-color: var(--primary-color);
        animation: spin 0.6s linear infinite;
    }
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
</script>