<?php
ob_start();
require_once __DIR__ . '/../../config.php';

// 权限检查
if (!isAdmin()) {
    header('Location: /m/');
    exit;
}

$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($user_id <= 0) {
    header('Location: ?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) {
    header('Location: ?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 5
");
?>

<!-- 用户基本信息 -->
<div class="card" style="text-align: center;">
    <img src="https://api.iconify.design/mdi:account-circle.svg?color=%23667eea" width="70" height="70" alt="" style="border-radius: 50%;">
    <h3 style="margin: 10px 0 4px;"><?php echo htmlspecialchars($user['username']); ?></h3>
    <p style="color: #999; font-size: 14px; margin-bottom: 10px;">
        <img src="https://api.iconify.design/mdi:email.svg?color=%23999" width="14" height="14" style="vertical-align: middle;" alt="">
        <?php echo htmlspecialchars($user['email']); ?>
    </p>
    <div style="display: flex; justify-content: center; gap: 8px; flex-wrap: wrap;">
        <span style="background: #667eea15; color: #667eea; padding: 4px 12px; border-radius: 20px; font-size: 12px;">
            <?php echo $user['role'] == 'admin' ? '管理员' : '普通用户'; ?>
        </span>
        <span style="background: <?php echo $user['status'] ? '#10b98115' : '#ef444415'; ?>; color: <?php echo $user['status'] ? '#10b981' : '#ef4444'; ?>; padding: 4px 12px; border-radius: 20px; font-size: 12px;">
            <?php echo $user['status'] ? '正常' : '禁用'; ?>
        </span>
    </div>
</div>

<!-- 账户信息 -->
<div class="card">
    <div style="display: flex; justify-content: space-around; text-align: center;">
        <div>
            <div style="font-size: 22px; font-weight: 700; color: #10b981;">¥<?php echo number_format($user['balance'], 2); ?></div>
            <div style="color: #999; font-size: 12px;">账户余额</div>
        </div>
        <div>
            <div style="font-size: 22px; font-weight: 700; color: #8b5cf6;"><?php echo htmlspecialchars($user['group_name'] ?? '普通会员'); ?></div>
            <div style="color: #999; font-size: 12px;">会员等级</div>
        </div>
        <div>
            <div style="font-size: 22px; font-weight: 700; color: #667eea;"><?php echo date('Y-m-d', strtotime($user['created_at'])); ?></div>
            <div style="color: #999; font-size: 12px;">注册时间</div>
        </div>
    </div>
</div>

<!-- 统计数据 -->
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
    <div class="card" style="text-align: center;">
        <img src="https://api.iconify.design/mdi:package.svg?color=%23667eea" width="28" height="28" alt="">
        <div style="font-size: 24px; font-weight: 700; color: #667eea;"><?php echo $order_stats['total_orders'] ?? 0; ?></div>
        <div style="color: #999; font-size: 12px;">总订单</div>
    </div>
    <div class="card" style="text-align: center;">
        <img src="https://api.iconify.design/mdi:cash-multiple.svg?color=%23f59e0b" width="28" height="28" alt="">
        <div style="font-size: 24px; font-weight: 700; color: #f59e0b;">¥<?php echo number_format($order_stats['total_amount'] ?? 0, 2); ?></div>
        <div style="color: #999; font-size: 12px;">总消费</div>
    </div>
    <div class="card" style="text-align: center;">
        <img src="https://api.iconify.design/mdi:key.svg?color=%2310b981" width="28" height="28" alt="">
        <div style="font-size: 24px; font-weight: 700; color: #10b981;"><?php echo $license_count; ?></div>
        <div style="color: #999; font-size: 12px;">授权码</div>
    </div>
    <div class="card" style="text-align: center;">
        <img src="https://api.iconify.design/mdi:ticket.svg?color=%23ef4444" width="28" height="28" alt="">
        <div style="font-size: 24px; font-weight: 700; color: #ef4444;"><?php echo $ticket_count; ?></div>
        <div style="color: #999; font-size: 12px;">工单</div>
    </div>
</div>

<!-- 最近余额变动 -->
<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
        <h3 style="font-size: 15px;">最近余额变动</h3>
        <a href="?page=user_balance&id=<?php echo $user_id; ?>" style="color: #667eea; font-size: 13px; text-decoration: none;">查看全部 ›</a>
    </div>
    
    <?php if (empty($balance_logs)): ?>
        <p style="text-align: center; color: #999; padding: 20px;">暂无记录</p>
    <?php else: ?>
        <?php foreach ($balance_logs as $log): ?>
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #f0f0f0;">
            <div>
                <div style="font-size: 13px;"><?php echo htmlspecialchars($log['remark'] ?: ($log['type'] == 'recharge' ? '充值' : '消费')); ?></div>
                <div style="font-size: 11px; color: #999;"><?php echo date('m-d H:i', strtotime($log['created_at'])); ?></div>
            </div>
            <span style="font-weight: 600; color: <?php echo $log['amount'] > 0 ? '#10b981' : '#ef4444'; ?>;">
                <?php echo $log['amount'] > 0 ? '+' : ''; ?>¥<?php echo number_format($log['amount'], 2); ?>
            </span>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- 操作按钮 -->
<div style="display: flex; flex-direction: column; gap: 10px;">
    <button class="btn btn-primary" style="width:100%;" 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=white" width="18" height="18" alt="">
            禁用用户
        <?php else: ?>
            <img src="https://api.iconify.design/mdi:account-check.svg?color=white" width="18" height="18" alt="">
            启用用户
        <?php endif; ?>
    </button>
    <button class="btn" style="width:100%; background:#f5f5f5;" onclick="if(confirm('确定重置密码吗？')) location.href='?page=user_reset_password&id=<?php echo $user_id; ?>'">
        <img src="https://api.iconify.design/mdi:key.svg?color=%23666" width="18" height="18" alt="">
        重置密码
    </button>
</div>

<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) {
                showToast('状态已更新', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(() => showToast('网络错误', 'error'));
    }
}
</script>