<?php
session_start();
require_once '../config.php';
require_once 'level_check.php';

// 检查登录状态
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// 获取用户基础信息
$stmt = mysqli_prepare($conn, "SELECT id, username, qq, avatar, created_at, coins, last_check_in, level FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);

if (!$user) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// --- 签到统计逻辑 ---
$total_check_ins = 0;
$stmt_total = mysqli_prepare($conn, "SELECT COUNT(id) as total FROM check_in_logs WHERE user_id = ?");
mysqli_stmt_bind_param($stmt_total, "i", $user_id);
mysqli_stmt_execute($stmt_total);
$res_total = mysqli_stmt_get_result($stmt_total);
if ($row_total = mysqli_fetch_assoc($res_total)) {
    $total_check_ins = $row_total['total'];
}

$consecutive_days = 0;
$last_check_in = $user['last_check_in'];
if ($last_check_in) {
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime("-1 day"));
    if ($last_check_in == $today || $last_check_in == $yesterday) {
        $stmt_con = mysqli_prepare($conn, "SELECT DISTINCT DATE(create_time) as check_date FROM check_in_logs WHERE user_id = ? AND create_time >= DATE_SUB(NOW(), INTERVAL 30 DAY) ORDER BY check_date DESC");
        mysqli_stmt_bind_param($stmt_con, "i", $user_id);
        mysqli_stmt_execute($stmt_con);
        $res_con = mysqli_stmt_get_result($stmt_con);
        $dates = [];
        while($row = mysqli_fetch_assoc($res_con)) { $dates[] = $row['check_date']; }
        if (!empty($dates)) {
            $expected_date = ($last_check_in == $today) ? $today : $yesterday;
            foreach ($dates as $d) {
                if ($d == $expected_date) {
                    $consecutive_days++;
                    $expected_date = date('Y-m-d', strtotime($expected_date . " -1 day"));
                } else { break; }
        }
        }
    }
}

// --- 等级显示逻辑 (修正版) ---
$user_level = $user['level'] ?? 0;

// 1. 计算总累积量
$stmt_acc = mysqli_prepare($conn, "SELECT SUM(ABS(change_amount)) as total_acc FROM coin_logs WHERE user_id = ?");
mysqli_stmt_bind_param($stmt_acc, "i", $user_id);
mysqli_stmt_execute($stmt_acc);
$res_acc = mysqli_stmt_get_result($stmt_acc);
$row_acc = mysqli_fetch_assoc($res_acc);
$total_accumulated = $row_acc['total_acc'] ?? 0;

// 2. 计算当前等级已经消耗了多少累积量
$current_level_cost = 0;
for($i=0; $i<$user_level; $i++) {
    $current_level_cost += getRequiredCoinsForNextLevel($i);
}

// 3. 下一级需要的币数
$next_level_need = getRequiredCoinsForNextLevel($user_level);

// 4. 当前进度
$progress_value = max(0, $total_accumulated - $current_level_cost);
$progress_percent = 0;
if ($next_level_need > 0) {
    $progress_percent = min(100, ($progress_value / $next_level_need) * 100);
} else {
    $progress_percent = 100; // 满级
}

// 5. 计算升级还需多少
$coins_needed_for_next = max(0, $next_level_need - $progress_value);

// 颜色与图标配置
$level_color = '#6c757d'; // 默认灰色
$level_icon = 'V';
if ($user_level >= 10) { $level_color = '#ff4757'; $level_icon = '👑V'; } // 红色
elseif ($user_level >= 7) { $level_color = '#ff9f43'; } // 橙色
elseif ($user_level >= 4) { $level_color = '#9b59b6'; } // 紫色
elseif ($user_level >= 1) { $level_color = '#3498db'; } // 蓝色

// 判断今天是否已签到
$today = date('Y-m-d');
$is_checked_in = ($user['last_check_in'] === $today);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
    <style>
        body { background-color: #f4f6f9; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; }
        .home-container { max-width: 500px; margin: 50px auto; background: #fff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); text-align: center; }
        
        .avatar-box { margin-bottom: 20px; position: relative; display: inline-block; }
        .avatar-box img { width: 100px; height: 100px; border-radius: 50%; border: 3px solid #fff; box-shadow: 0 2px 10px rgba(0,0,0,0.1); object-fit: cover; background: #eee; }
        .avatar-edit-btn { position: absolute; bottom: 0; right: 0; width: 30px; height: 30px; background: #007bff; border-radius: 50%; border: 2px solid #fff; color: white; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; transition: transform 0.2s; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
        .avatar-edit-btn:hover { transform: scale(1.1); }

        /* === 1. 顶部信息容器 (包含名字和等级) === */
        .top-info-container {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin-bottom: 10px;
        }

        .user-name-display {
            font-size: 22px;
            color: #333;
            font-weight: bold;
        }

        .edit-name-btn { 
            font-size: 14px; 
            color: #999; 
            cursor: pointer; 
            transition: color 0.2s; 
            background: none; 
            border: none; 
            margin-left: 5px;
        }
        .edit-name-btn:hover { color: #007bff; }

        /* === 2. 等级徽章样式 === */
        .level-badge-inline { 
            background: #eee; 
            color: #666; 
            padding: 2px 8px; 
            border-radius: 4px; 
            font-size: 14px; 
            font-weight: bold;
            flex-shrink: 0;
            border-radius: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            vertical-align: middle; /* 垂直居中 */
        }

        /* === 3. 进度条区域 (独立在下方) === */
        .progress-section {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
            padding: 0 40px; /* 两边留点间距 */
        }

        .progress-box {
            width: 100%;
            max-width: 250px;
            text-align: center;
        }

        .progress-bg { 
            background: #f0f2f5; 
            border-radius: 10px; 
            height: 10px; 
            overflow: hidden; 
            margin-bottom: 4px;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        
        /* === 4. 进度条滑动动画 === */
        .progress-fill { 
            height: 100%; 
            width: 0; /* 初始宽度设为0 */
            border-radius: 10px;
            transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑滑动动画 */
            -webkit-transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .progress-text { 
            font-size: 11px; 
            color: #888; 
            display: block;
            margin-top: 2px;
        }

        .stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px; }
        .stat-card { background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; }
        .stat-num { font-size: 24px; font-weight: bold; color: #007bff; display: block; margin-bottom: 5px; }
        .stat-label { font-size: 12px; color: #888; }

        .coins-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; padding: 15px; margin: 20px 0; color: white; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4); }
        .coins-info { text-align: left; }
        .coins-label { font-size: 12px; opacity: 0.9; margin-bottom: 4px; }
        .coins-num { font-size: 24px; font-weight: bold; }
        .coins-unit { font-size: 12px; margin-left: 4px; }
        
        .action-btns { display: flex; gap: 10px; }
        .btn-checkin { background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.4); padding: 8px 15px; border-radius: 20px; cursor: pointer; font-weight: bold; transition: all 0.3s; font-size: 14px; text-decoration: none; display: inline-block; }
        .btn-checkin:hover { background: rgba(255,255,255,0.3); }
        .btn-checkin:disabled { background: rgba(0,0,0,0.1); border-color: rgba(255,255,255,0.1); cursor: not-allowed; opacity: 0.8; }
        .btn-buy { background: #ffc107; color: #333; border: none; padding: 8px 15px; border-radius: 20px; font-weight: bold; font-size: 14px; text-decoration: none; transition: opacity 0.3s; }
        .btn-buy:hover { opacity: 0.9; }
        
        .func-links { display: flex; justify-content: center; gap: 15px; margin: 20px 0; }
        .btn-link { background: #fff; border: 1px solid #ddd; padding: 10px 20px; border-radius: 8px; color: #555; text-decoration: none; font-size: 14px; transition: all 0.3s; display: flex; align-items: center; gap: 5px; }
        .btn-link:hover { border-color: #007bff; color: #007bff; background: #f0f7ff; }

        .user-info-card { background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: left; }
        .info-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px dashed #eee; font-size: 14px; }
        .info-item:last-child { border-bottom: none; }
        .info-label { color: #888; }
        .info-value { font-weight: bold; font-size: 15px; }
        .value-id { color: #007bff; }
        .value-qq { color: #6f42c1; }
        .value-time { color: #28a745; }
        
        .qq-container { display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
        .btn-mini-change { font-size: 12px; padding: 2px 8px; background: #fff; border: 1px solid #6f42c1; color: #6f42c1; border-radius: 4px; text-decoration: none; cursor: pointer; transition: all 0.2s; font-weight: bold; }
        .btn-mini-change:hover { background: #6f42c1; color: #fff; }

        .btn-group { margin-top: 25px; display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }
        .btn-action { padding: 10px 20px; border-radius: 20px; text-decoration: none; color: #fff; font-size: 14px; transition: opacity 0.3s; cursor: pointer; border: none; }
        .btn-action:hover { opacity: 0.9; }
        .btn-logout { background-color: #6c757d; }
        .btn-changepwd { background-color: #007bff; }
        .btn-bind { background-color: #28a7de; }

        /* 弹窗 */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 999; }
        .modal-content { background: #fff; padding: 20px; border-radius: 10px; width: 90%; max-width: 400px; text-align: center; position: relative;}
        .modal-close { position: absolute; top: 10px; right: 15px; cursor: pointer; color: #999; font-size: 20px; }
        .modal-btn { margin-top: 15px; padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; }
        .modal-btn:disabled { background: #ccc; cursor: not-allowed; }
        .form-group { margin-bottom: 15px; text-align: left; }
        .form-group input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; }
        .form-tip { font-size: 12px; color: #999; margin-top: 5px; }
        .price-tip { color: #e94560; font-size: 12px; margin-top: 5px; }
    </style>
</head>
<body>

<div class="home-container">
    <div class="avatar-box">
        <img id="userAvatar" src="<?php 
            if (!empty($user['avatar'])) {
                echo '../' . htmlspecialchars($user['avatar']);
            } elseif (!empty($user['qq'])) {
                echo 'https://q.qlogo.cn/g?b=qq&nk=' . htmlspecialchars($user['qq']) . '&s=100';
            } else {
                echo 'https://picsum.photos/100/100?grayscale';
            }
        ?>" alt="用户头像">
        <div class="avatar-edit-btn" onclick="document.getElementById('avatarInput').click()">✎</div>
        <input type="file" id="avatarInput" accept="image/*" style="display:none">
    </div>

    <!-- 1. 顶部信息：名字 + 等级 -->
    <div class="top-info-container">
        <!-- 等级徽章 -->
        <span class="level-badge-inline" style="background: <?php echo $level_color; ?>; color: white;">
            <?php echo $level_icon . $user_level; ?>
        </span>
        
        <!-- 用户名 -->
        <span id="displayUsername" class="user-name-display"><?php echo htmlspecialchars($user['username']); ?></span>
        
        <!-- 修改按钮 -->
        <button class="edit-name-btn" onclick="openNameModal()" title="修改昵称">✎</button>
    </div>

    <!-- 2. 进度条区域 (独立在下方) -->
    <div class="progress-section">
        <div class="progress-box">
            <div class="progress-bg">
                <!-- 动画将通过JS触发 -->
                <div id="levelProgressFill" class="progress-fill" style="background: <?php echo $level_color; ?>;"></div>
            </div>
            <span class="progress-text">
                <?php if ($user_level >= 100): ?>
                    已达满级
                <?php else: ?>
                    升级还需: <?php echo $coins_needed_for_next; ?> 币
                <?php endif; ?>
            </span>
        </div>
    </div>

    <!-- 签到统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <span class="stat-num"><?php echo $total_check_ins; ?></span>
            <span class="stat-label">累计签到 (天)</span>
        </div>
        <div class="stat-card">
            <span class="stat-num"><?php echo $consecutive_days; ?></span>
            <span class="stat-label">连续签到 (天)</span>
        </div>
    </div>

    <!-- 小马币与签到 -->
    <div class="coins-card">
        <div class="coins-info">
            <div class="coins-label">我的小马币</div>
            <div class="coins-num">
                <span id="coinNum"><?php echo intval($user['coins']); ?></span>
                <span class="coins-unit">个</span>
            </div>
        </div>
        <div class="action-btns">
            <?php if ($is_checked_in): ?>
                <button class="btn-checkin" disabled>今日已签</button>
            <?php else: ?>
                <a href="qd.php" class="btn-checkin">签到 +2</a>
            <?php endif; ?>
            <a href="gm.php" class="btn-buy">购买</a>
        </div>
    </div>

    <!-- 功能链接 -->
    <div class="func-links">
        <a href="syxq.php" class="btn-link">📊 收益详情</a>
    </div>

    <div class="user-info-card">
        <div class="info-item">
            <span class="info-label">用户 ID</span>
            <span class="info-value value-id"><?php echo $user['id']; ?></span>
        </div>
        <div class="info-item">
            <span class="info-label">QQ 号</span>
            <div class="qq-container">
                <span class="info-value value-qq"><?php echo htmlspecialchars($user['qq'] ?: '未填写'); ?></span>
                <?php if(!empty($user['qq'])): ?>
                    <a href="bd.php?qq=<?php echo htmlspecialchars($user['qq']); ?>" class="btn-mini-change">换绑</a>
                <?php endif; ?>
            </div>
        </div>
        <div class="info-item">
            <span class="info-label">注册时间</span>
            <span class="info-value value-time"><?php echo $user['created_at'] ? date('Y-m-d H:i', strtotime($user['created_at'])) : '未记录'; ?></span>
        </div>
    </div>

    <div class="btn-group">
        <a href="mm.php" class="btn-action btn-changepwd">修改密码</a>
        <a href="bd.php" class="btn-action btn-bind">账号绑定</a>
        <a href="logout.php" class="btn-action btn-logout">退出登录</a>
    </div>
</div>

<!-- 头像裁剪弹窗 -->
<div class="modal" id="avatarModal">
    <div class="modal-content">
        <span class="modal-close" onclick="closeModal('avatarModal')">×</span>
        <div class="modal-title">修改头像</div>
        <div style="max-height: 300px; margin-bottom: 15px;">
            <img id="cropImage" style="max-width: 100%; display: block;">
        </div>
        <div class="price-tip">修改头像需消耗 5 个小马币</div>
        <button class="modal-btn" onclick="uploadAvatar()">确认保存</button>
    </div>
</div>

<!-- 修改昵称弹窗 -->
<div class="modal" id="nameModal">
    <div class="modal-content">
        <span class="modal-close" onclick="closeModal('nameModal')">×</span>
        <div class="modal-title">修改昵称</div>
        <div class="form-group">
            <input type="text" id="newUsername" placeholder="请输入新昵称" maxlength="12" value="<?php echo htmlspecialchars($user['username']); ?>">
            <div class="form-tip">昵称不能超过12个字。修改需消耗 15 个小马币。</div>
        </div>
        <button class="modal-btn" onclick="saveUsername()">保存</button>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
<script>
var cropper;

// --- 页面加载完成后触发进度条动画 ---
window.onload = function() {
    var progressFill = document.getElementById('levelProgressFill');
    if (progressFill) {
        // 这里的数值是PHP后端计算好的
        var targetWidth = <?php echo $progress_percent; ?>;
        // 延迟一点点执行，让CSS加载完毕，效果更明显
        setTimeout(function() {
            progressFill.style.width = targetWidth + '%';
        }, 100);
    }
};

// --- 通用弹窗 ---
function openModal(id) { document.getElementById(id).style.display = 'flex'; }
function closeModal(id) { document.getElementById(id).style.display = 'none'; }

// --- 1. 头像修改 ---
document.getElementById('avatarInput').addEventListener('change', function(e) {
    var file = e.target.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onload = function(event) {
            openModal('avatarModal');
            var cropImg = document.getElementById('cropImage');
            cropImg.src = event.target.result;
            if (cropper) cropper.destroy();
            cropper = new Cropper(cropImg, { aspectRatio: 1, viewMode: 1 });
        };
        reader.readAsDataURL(file);
    }
});

function uploadAvatar() {
    if (!cropper) return alert('请先选择图片');
    var canvas = cropper.getCroppedCanvas({ width: 200, height: 200 });
    if (!canvas) return alert('图片处理失败');
    var dataUrl = canvas.toDataURL('image/jpeg', 0.9);
    
    var btn = document.querySelector('#avatarModal .modal-btn');
    btn.innerText = '上传中...'; btn.disabled = true;

    $.ajax({
        url: 'upload_avatar.php', type: 'POST', data: { image_data: dataUrl }, dataType: 'json',
        success: function(res) {
            btn.innerText = '确认保存'; btn.disabled = false;
            if (res.status === 'success') {
                $('#userAvatar').attr('src', res.url + '?t=' + new Date().getTime());
                $('#coinNum').text(res.coins);
                closeModal('avatarModal');
                alert('头像更新成功！消耗了5个币');
                if(res.level_up) { alert('恭喜！您的等级提升到了 V' + res.level_up); location.reload(); }
            } else { alert('上传失败: ' + res.message); }
        },
        error: function() { btn.innerText = '确认保存'; btn.disabled = false; alert('网络错误'); }
    });
}

// --- 2. 昵称修改 ---
function openNameModal() { openModal('nameModal'); }

function saveUsername() {
    var newName = document.getElementById('newUsername').value.trim();
    if (!newName) return alert('昵称不能为空');
    if (newName.length > 12) return alert('昵称不能超过12个字');
    
    var btn = document.querySelector('#nameModal .modal-btn');
    btn.innerText = '保存中...'; btn.disabled = true;

    $.post('ajax.php', { action: 'change_username', username: newName }, function(res) {
        btn.innerText = '保存'; btn.disabled = false;
        if (res.status === 'success') {
            document.getElementById('displayUsername').innerText = newName;
            $('#coinNum').text(res.coins);
            closeModal('nameModal');
            alert('昵称修改成功！消耗了15个币');
            if(res.level_up) { alert('恭喜！您的等级提升到了 V' + res.level_up); location.reload(); }
        } else { alert('修改失败: ' + res.message); }
    }, 'json');
}
</script>
</body>
</html>
