<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-28
 */


/**
 * 个人资料
 */

$error = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nickname = trim($_POST['nickname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $avatar = trim($_POST['avatar'] ?? '');

    if (empty($nickname)) {
        $error = '昵称不能为空';
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } else {
        $db->update('member', [
            'nickname' => $nickname,
            'email' => $email,
            'phone' => $phone,
            'avatar' => $avatar,
            'update_time' => time()
        ], 'id = ?', [$_SESSION['member_id']]);

        $_SESSION['member_nickname'] = $nickname;
        $success = true;
    }
}

$member = $db->fetch("SELECT * FROM {$db->table('member')} WHERE id = ?", [$_SESSION['member_id']]);
?>
<div class="page-header">
    <h1 class="page-title">
        <i class="icon-user"></i>
        个人资料
    </h1>
</div>
<div class="page-content">
    <?php if ($error): ?>
    <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert alert-success">✓ 保存成功</div>
    <?php endif; ?>

    <form method="post" class="profile-form">
        <div class="form-row">
            <div class="form-group">
                <label>用户名</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($member['username']); ?>" disabled>
                <p class="form-tip">用户名不可修改</p>
            </div>
            <div class="form-group">
                <label>昵称</label>
                <input type="text" name="nickname" class="form-control" value="<?php echo htmlspecialchars($member['nickname'] ?? ''); ?>" required>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>邮箱</label>
                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($member['email'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>手机号</label>
                <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($member['phone'] ?? ''); ?>">
            </div>
        </div>

        <div class="form-group">
            <label>头像</label>
            <div class="avatar-upload">
                <div class="avatar-preview" id="avatarPreview">
                    <?php if (!empty($member['avatar'])): ?>
                    <img src="<?php echo htmlspecialchars($member['avatar']); ?>" alt="当前头像" />
                    <?php else: ?>
                    <div class="avatar-placeholder"><i class="icon-user"></i></div>
                    <?php endif; ?>
                </div>
                <div class="avatar-actions">
                    <input type="text" name="avatar" id="avatarInput" class="form-control" value="<?php echo htmlspecialchars($member['avatar'] ?? ''); ?>" placeholder="输入头像图片地址">
                    <button type="button" class="btn btn-outline" id="uploadAvatarBtn">
                        <i class="icon-upload"></i> 上传本地图片
                    </button>
                    <input type="file" id="avatarFile" accept="image/*" style="display:none;" />
                    <p class="form-tip">支持JPG/PNG/GIF，建议正方形图片</p>
                </div>
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary">保存修改</button>
        </div>
    </form>
</div>

<style>
.profile-form { max-width: 700px; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.form-tip { font-size: 12px; color: #999; margin-top: 4px; }
.form-actions { margin-top: 24px; }
.alert {
    padding: 12px 16px;
    border-radius: 8px;
    font-size: 14px;
    margin-bottom: 20px;
}
.alert-error { background: #fee2e2; color: #dc2626; }
.alert-success { background: #d1fae5; color: #059669; }

/* 头像上传 */
.avatar-upload { display: flex; gap: 20px; align-items: flex-start; }
.avatar-preview {
    width: 100px; height: 100px; border-radius: 50%; overflow: hidden;
    border: 3px solid #e5e7eb; background: #f9fafb;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
}
.avatar-preview img { width: 100%; height: 100%; object-fit: cover; }
.avatar-placeholder { font-size: 40px; color: #cbd5e1; }
.avatar-actions { flex: 1; }
.avatar-actions .form-control { margin-bottom: 10px; }
.btn-outline {
    background: #fff; border: 2px solid #e5e7eb; color: #374151;
    padding: 8px 16px; border-radius: 8px; cursor: pointer;
    display: inline-flex; align-items: center; gap: 6px;
    transition: all 0.2s;
}
.btn-outline:hover { border-color: #10b981; color: #10b981; }
</style>

<script>
document.getElementById('uploadAvatarBtn').addEventListener('click', function() {
    document.getElementById('avatarFile').click();
});

document.getElementById('avatarFile').addEventListener('change', function(e) {
    var file = e.target.files[0];
    if (!file) return;

    if (!file.type.match(/^image\/(jpeg|jpg|png|gif|webp)$/)) {
        alert('请选择图片文件（JPG/PNG/GIF）');
        return;
    }

    var formData = new FormData();
    formData.append('file', file);
    formData.append('action', 'upload');
    formData.append('type', 'avatar');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/upload.php', true);
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            var percent = Math.round((e.loaded / e.total) * 100);
            document.getElementById('uploadAvatarBtn').innerHTML = '<i class="icon-loader"></i> 上传中 ' + percent + '%';
        }
    };
    xhr.onload = function() {
        try {
            var res = JSON.parse(xhr.responseText);
            if (res.code == 200) {
                var avatarUrl = res.url;
                document.getElementById('avatarInput').value = avatarUrl;
                document.getElementById('avatarPreview').innerHTML = '<img src="' + avatarUrl + '" alt="头像" />';
                document.getElementById('uploadAvatarBtn').innerHTML = '<i class="icon-upload"></i> 重新上传';
            } else {
                alert(res.msg || '上传失败');
                document.getElementById('uploadAvatarBtn').innerHTML = '<i class="icon-upload"></i> 上传本地图片';
            }
        } catch(e) {
            alert('上传失败');
            document.getElementById('uploadAvatarBtn').innerHTML = '<i class="icon-upload"></i> 上传本地图片';
        }
    };
    xhr.send(formData);
});

document.getElementById('avatarInput').addEventListener('input', function() {
    var url = this.value;
    var preview = document.getElementById('avatarPreview');
    if (url) {
        preview.innerHTML = '<img src="' + url + '" alt="头像" />';
    } else {
        preview.innerHTML = '<div class="avatar-placeholder"><i class="icon-user"></i></div>';
    }
});
</script>