<?php
requireAdmin();

$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($user_id <= 0) {
    redirect('?page=users');
    exit;
}

$user = $db->fetchOne("
    SELECT u.*, ug.name as group_name 
    FROM users u 
    LEFT JOIN user_groups ug ON u.group_id = ug.id 
    WHERE u.id = $user_id
");
if (!$user) {
    redirect('?page=users');
    exit;
}

// 获取用户订单统计
$order_stats = $db->fetchOne("
    SELECT 
        COUNT(*) as total_orders,
        SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) as total_amount,
        COUNT(CASE WHEN status = 'paid' THEN 1 END) as paid_orders
    FROM orders WHERE user_id = $user_id
");

// 获取用户授权码数量
$license_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses WHERE user_id = $user_id")['cnt'] ?? 0;

// 获取用户工单数量
$ticket_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id")['cnt'] ?? 0;

// 获取用户余额明细
$balance_logs = $db->fetchAll("
    SELECT * FROM balance_logs 
    WHERE user_id = $user_id 
    ORDER BY id DESC LIMIT 10
");
?>

<div class="user-detail">
    <div class="page-header">
        <h2>用户详情</h2>
        <a href="?page=users" class="btn btn-secondary">← 返回用户列表</a>
    </div>
    
    <!-- 基本信息卡片 -->
    <div class="info-card">
        <div class="info-header">
            <!--<div class="user-avatar">-->
            <!--    <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar">-->
            <!--</div>-->
            <div class="user-basic">
                <h3><?php echo htmlspecialchars($user['username']); ?></h3>
                <p><?php echo htmlspecialchars($user['email']); ?></p>
                <div class="user-tags">
                    <span class="tag"><?php echo $user['role'] == 'admin' ? '管理员' : ($user['role'] == 'employee' ? '员工' : '普通用户'); ?></span>
                    <?php if ($user['is_agent']): ?>
                        <span class="tag agent">代理商 (等级<?php echo $user['agent_level']; ?>)</span>
                    <?php endif; ?>
                    <span class="tag <?php echo $user['status'] ? 'active' : 'inactive'; ?>"><?php echo $user['status'] ? '正常' : '禁用'; ?></span>
                </div>
            </div>
        </div>
        <div class="info-stats">
            <div class="stat-item">
                <div class="stat-label">注册时间</div>
                <div class="stat-value"><?php echo $user['created_at']; ?></div>
            </div>
            <div class="stat-item">
                <div class="stat-label">账户余额</div>
                <div class="stat-value">¥<?php echo number_format($user['balance'], 2); ?></div>
            </div>
            <div class="stat-item">
                <div class="stat-label">会员等级</div>
                <div class="stat-value"><?php echo htmlspecialchars($user['group_name'] ?? '普通会员'); ?></div>
            </div>
        </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <h3>总订单数</h3>
            <div class="stat-value"><?php echo $order_stats['total_orders'] ?? 0; ?></div>
        </div>
        <div class="stat-card">
            <h3>已支付订单</h3>
            <div class="stat-value"><?php echo $order_stats['paid_orders'] ?? 0; ?></div>
        </div>
        <div class="stat-card">
            <h3>总消费金额</h3>
            <div class="stat-value">¥<?php echo number_format($order_stats['total_amount'] ?? 0, 2); ?></div>
        </div>
        <div class="stat-card">
            <h3>授权码数量</h3>
            <div class="stat-value"><?php echo $license_count; ?></div>
        </div>
        <div class="stat-card">
            <h3>工单数量</h3>
            <div class="stat-value"><?php echo $ticket_count; ?></div>
        </div>
    </div>
    
    <!-- 最近余额变动 -->
    <div class="section-box">
        <div class="section-header">
            <h3>最近余额变动</h3>
            <a href="?page=user_balance&id=<?php echo $user_id; ?>" class="btn-small">查看全部</a>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>金额</th>
                        <th>类型</th>
                        <th>备注</th>
                    </thead>
                <tbody>
                    <?php if (empty($balance_logs)): ?>
                        <tr><td colspan="4" style="text-align: center;">暂无余额变动记录</td></tr>
                    <?php else: ?>
                        <?php foreach ($balance_logs as $log): ?>
                            <tr>
                                <td><?php echo $log['created_at']; ?></td>
                                <td style="color: <?php echo $log['amount'] > 0 ? '#10b981' : '#ef4444'; ?>">
                                    <?php echo $log['amount'] > 0 ? '+' : ''; ?>¥<?php echo number_format($log['amount'], 2); ?>
                                </td>
                                <td><?php echo $log['type'] == 'recharge' ? '充值' : ($log['type'] == 'consume' ? '消费' : '退款'); ?></td>
                                <td><?php echo htmlspecialchars($log['remark'] ?: '-'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-secondary" onclick="toggleUserStatus(<?php echo $user['id']; ?>, <?php echo $user['status']; ?>)">
            <?php echo $user['status'] ? '🔴 禁用用户' : '🟢 启用用户'; ?>
        </button>
        <button class="btn btn-secondary" onclick="if(confirm('确定重置密码吗？新密码将发送到用户邮箱')) location.href='?page=user_reset_password&id=<?php echo $user_id; ?>'">
            🔑 重置密码
        </button>
        <?php if ($user['role'] == 'user' && !$user['is_agent']): ?>
            <button class="btn btn-secondary" onclick="setAsAgent(<?php echo $user['id']; ?>)">
                🤝 设为代理商
            </button>
        <?php endif; ?>
    </div>
</div>

<style>
.user-detail {
    max-width: 1000px;
    margin: 0 auto;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.info-card {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 24px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
}
.info-header {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.user-avatar img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
}
.user-basic h3 {
    font-size: 24px;
    margin-bottom: 5px;
}
.user-basic p {
    color: var(--text-secondary);
    margin-bottom: 10px;
}
.user-tags {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.tag {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    background: var(--bg-secondary);
}
.tag.agent {
    background: #fef3c7;
    color: #92400e;
}
.tag.active {
    background: #d1fae5;
    color: #065f46;
}
.tag.inactive {
    background: #fee2e2;
    color: #991b1b;
}
.info-stats {
    display: flex;
    gap: 30px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
    flex-wrap: wrap;
}
.stat-item .stat-label {
    font-size: 12px;
    color: var(--text-muted);
}
.stat-item .stat-value {
    font-size: 16px;
    font-weight: 600;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: 12px;
    padding: 15px;
    text-align: center;
    border: 1px solid var(--border-color);
}
.stat-card h3 {
    font-size: 13px;
    color: var(--text-muted);
    margin-bottom: 5px;
}
.stat-card .stat-value {
    font-size: 24px;
    font-weight: 600;
}
.section-box {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
}
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
}
.action-buttons {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    justify-content: center;
}
.btn-small {
    padding: 5px 12px;
    font-size: 12px;
    background: var(--primary-color);
    color: white;
    border-radius: 6px;
    text-decoration: none;
}
</style>

<script>
function toggleUserStatus(id, currentStatus) {
    const newStatus = currentStatus == 1 ? 0 : 1;
    if (confirm('确定要' + (newStatus == 1 ? '启用' : '禁用') + '此用户吗？')) {
        fetch('/api/admin_toggle_user_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${newStatus}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast('状态已更新', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => window.showToast('网络错误', 'error'));
    }
}

function setAsAgent(id) {
    if (confirm('确定将此用户设为代理商吗？')) {
        fetch('/api/admin_set_as_agent.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast('设置成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => window.showToast('网络错误', 'error'));
    }
}
</script>