<?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>
            <img src="https://api.iconify.design/mdi:account-details.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            用户详情
        </h2>
        <a href="?page=users" class="btn btn-secondary">
            <img src="https://api.iconify.design/mdi:arrow-left.svg?color=currentColor" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
            返回用户列表
        </a>
    </div>
    
    <!-- 基本信息卡片 -->
    <div class="info-card">
        <div class="info-header">
            <div class="user-avatar-large">
                <img src="https://api.iconify.design/mdi:account-circle.svg?color=%23667eea" width="80" height="80" alt="">
            </div>
            <div class="user-basic">
                <h3><?php echo htmlspecialchars($user['username']); ?></h3>
                <p>
                    <img src="https://api.iconify.design/mdi:email.svg?color=%236b7280" width="14" height="14" style="margin-right: 4px;" alt="">
                    <?php echo htmlspecialchars($user['email']); ?>
                </p>
                <div class="user-tags">
                    <span class="tag tag-role">
                        <img src="https://api.iconify.design/mdi:shield-account.svg?color=currentColor" width="12" height="12" style="margin-right: 4px;" alt="">
                        <?php echo $user['role'] == 'admin' ? '管理员' : ($user['role'] == 'employee' ? '员工' : '普通用户'); ?>
                    </span>
                    <?php if ($user['is_agent']): ?>
                        <span class="tag tag-agent">
                            <img src="https://api.iconify.design/mdi:handshake.svg?color=currentColor" width="12" height="12" style="margin-right: 4px;" alt="">
                            代理商 (等级<?php echo $user['agent_level']; ?>)
                        </span>
                    <?php endif; ?>
                    <span class="tag tag-<?php echo $user['status'] ? 'active' : 'inactive'; ?>">
                        <span class="status-dot"></span>
                        <?php echo $user['status'] ? '正常' : '禁用'; ?>
                    </span>
                </div>
            </div>
        </div>
        <div class="info-stats">
            <div class="stat-item">
                <div class="stat-icon">
                    <img src="https://api.iconify.design/mdi:calendar.svg?color=%23667eea" width="20" height="20" alt="">
                </div>
                <div class="stat-content">
                    <div class="stat-label">注册时间</div>
                    <div class="stat-value"><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></div>
                </div>
            </div>
            <div class="stat-item">
                <div class="stat-icon">
                    <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="20" height="20" alt="">
                </div>
                <div class="stat-content">
                    <div class="stat-label">账户余额</div>
                    <div class="stat-value">¥<?php echo number_format($user['balance'], 2); ?></div>
                </div>
            </div>
            <div class="stat-item">
                <div class="stat-icon">
                    <img src="https://api.iconify.design/mdi:account-group.svg?color=%238b5cf6" width="20" height="20" alt="">
                </div>
                <div class="stat-content">
                    <div class="stat-label">会员等级</div>
                    <div class="stat-value"><?php echo htmlspecialchars($user['group_name'] ?? '普通会员'); ?></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-icon">
                <img src="https://api.iconify.design/mdi:package.svg?color=%23667eea" width="24" height="24" alt="">
            </div>
            <div class="stat-card-content">
                <h3>总订单数</h3>
                <div class="stat-card-value"><?php echo $order_stats['total_orders'] ?? 0; ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="24" height="24" alt="">
            </div>
            <div class="stat-card-content">
                <h3>已支付订单</h3>
                <div class="stat-card-value"><?php echo $order_stats['paid_orders'] ?? 0; ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon">
                <img src="https://api.iconify.design/mdi:cash-multiple.svg?color=%23f59e0b" width="24" height="24" alt="">
            </div>
            <div class="stat-card-content">
                <h3>总消费金额</h3>
                <div class="stat-card-value">¥<?php echo number_format($order_stats['total_amount'] ?? 0, 2); ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon">
                <img src="https://api.iconify.design/mdi:key.svg?color=%238b5cf6" width="24" height="24" alt="">
            </div>
            <div class="stat-card-content">
                <h3>授权码数量</h3>
                <div class="stat-card-value"><?php echo $license_count; ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-icon">
                <img src="https://api.iconify.design/mdi:ticket.svg?color=%23ef4444" width="24" height="24" alt="">
            </div>
            <div class="stat-card-content">
                <h3>工单数量</h3>
                <div class="stat-card-value"><?php echo $ticket_count; ?></div>
            </div>
        </div>
    </div>
    
    <!-- 最近余额变动 -->
    <div class="section-box">
        <div class="section-header">
            <h3>
                <img src="https://api.iconify.design/mdi:history.svg?color=%23667eea" width="20" height="20" style="vertical-align: middle; margin-right: 8px;" alt="">
                最近余额变动
            </h3>
            <a href="?page=user_balance&id=<?php echo $user_id; ?>" class="btn-small">
                查看全部
                <img src="https://api.iconify.design/mdi:arrow-right.svg?color=white" width="14" height="14" style="margin-left: 4px;" alt="">
            </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">
                                <div class="empty-row">
                                    <img src="https://api.iconify.design/mdi:information.svg?color=%239ca3af" width="24" height="24" alt="">
                                    暂无余额变动记录
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($balance_logs as $log): ?>
                            <tr>
                                <td><?php echo date('Y-m-d H:i', strtotime($log['created_at'])); ?></td>
                                <td class="amount-<?php echo $log['amount'] > 0 ? 'positive' : 'negative'; ?>">
                                    <?php echo $log['amount'] > 0 ? '+' : ''; ?>¥<?php echo number_format($log['amount'], 2); ?>
                                </td>
                                <td>
                                    <span class="type-badge type-<?php echo $log['type']; ?>">
                                        <?php 
                                            if ($log['type'] == 'recharge') {
                                                echo '<img src="https://api.iconify.design/mdi:plus-circle.svg?color=%2310b981" width="12" height="12" style="margin-right: 4px;" alt="">充值';
                                            } elseif ($log['type'] == 'consume') {
                                                echo '<img src="https://api.iconify.design/mdi:minus-circle.svg?color=%23f59e0b" width="12" height="12" style="margin-right: 4px;" alt="">消费';
                                            } else {
                                                echo '<img src="https://api.iconify.design/mdi:refresh.svg?color=%23667eea" width="12" height="12" style="margin-right: 4px;" alt="">退款';
                                            }
                                        ?>
                                    </span>
                                </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 if ($user['status']): ?>
                <img src="https://api.iconify.design/mdi:account-cancel.svg?color=%23ef4444" width="18" height="18" style="margin-right: 6px;" alt="">
                禁用用户
            <?php else: ?>
                <img src="https://api.iconify.design/mdi:account-check.svg?color=%2310b981" width="18" height="18" style="margin-right: 6px;" alt="">
                启用用户
            <?php endif; ?>
        </button>
        <button class="btn btn-secondary" onclick="if(confirm('确定重置密码吗？新密码将发送到用户邮箱')) location.href='?page=user_reset_password&id=<?php echo $user_id; ?>'">
            <img src="https://api.iconify.design/mdi:key.svg?color=%23f59e0b" width="18" height="18" style="margin-right: 6px;" alt="">
            重置密码
        </button>
        <?php if ($user['role'] == 'user' && !$user['is_agent']): ?>
            <button class="btn btn-secondary" onclick="setAsAgent(<?php echo $user['id']; ?>)">
                <img src="https://api.iconify.design/mdi:handshake.svg?color=%238b5cf6" width="18" height="18" style="margin-right: 6px;" alt="">
                设为代理商
            </button>
        <?php endif; ?>
    </div>
</div>

<style>
.user-detail {
    max-width: 1000px;
    margin: 0 auto;
    padding: 4px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.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);
}

/* 基本信息卡片 */
.info-card {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 28px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.info-header {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
    flex-wrap: wrap;
}
.user-avatar-large {
    flex-shrink: 0;
}
.user-avatar-large img {
    display: block;
    border-radius: 50%;
}
.user-basic h3 {
    font-size: 26px;
    font-weight: 600;
    margin: 0 0 6px;
    color: var(--text-primary);
}
.user-basic p {
    display: flex;
    align-items: center;
    color: var(--text-secondary);
    margin: 0 0 14px;
    font-size: 15px;
}
.user-tags {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.tag {
    display: inline-flex;
    align-items: center;
    padding: 5px 14px;
    border-radius: 30px;
    font-size: 13px;
    font-weight: 500;
    background: var(--bg-secondary);
    color: var(--text-secondary);
}
.tag-role {
    background: #e0e7ff;
    color: #4338ca;
}
.tag-agent {
    background: #fef3c7;
    color: #92400e;
}
.tag-active {
    background: #d1fae5;
    color: #065f46;
}
.tag-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 6px;
}
.tag-active .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.tag-inactive .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

.info-stats {
    display: flex;
    gap: 40px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color);
    flex-wrap: wrap;
}
.stat-item {
    display: flex;
    align-items: center;
    gap: 14px;
}
.stat-icon {
    width: 44px;
    height: 44px;
    border-radius: 12px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
}
.stat-content .stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-bottom: 4px;
}
.stat-content .stat-value {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
}

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

/* 区块 */
.section-box {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 24px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
}
.section-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.btn-small {
    display: inline-flex;
    align-items: center;
    padding: 7px 16px;
    font-size: 13px;
    background: var(--primary-color);
    color: white;
    border-radius: 8px;
    text-decoration: none;
    transition: all 0.2s;
}
.btn-small:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}

/* 表格 */
.table-container {
    overflow-x: auto;
}
.data-table {
    width: 100%;
    border-collapse: collapse;
}
.data-table th {
    padding: 14px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
}
.data-table td {
    padding: 14px 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}
.amount-positive {
    color: #10b981;
    font-weight: 600;
}
.amount-negative {
    color: #ef4444;
    font-weight: 600;
}
.type-badge {
    display: inline-flex;
    align-items: center;
}
.empty-row {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 40px;
    color: var(--text-muted);
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 14px;
    flex-wrap: wrap;
    justify-content: center;
    padding: 10px 0;
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .info-stats {
        gap: 20px;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
}
@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
function toggleUserStatus(id, currentStatus) {
    const newStatus = currentStatus == 1 ? 0 : 1;
    const actionText = newStatus == 1 ? '启用' : '禁用';
    if (confirm('确定要' + actionText + '此用户吗？')) {
        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 && window.showToast('状态已更新', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast && window.showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => window.showToast && 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 && window.showToast('设置成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast && window.showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => window.showToast && window.showToast('网络错误', 'error'));
    }
}
</script>