<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 从zj表获取用户详细信息
$user_detail = $DB->get_row("SELECT * FROM `zj` WHERE `id`='{$user['id']}'");

// 获取用户资料，如果没有则为空
$user_realname = isset($user_detail['realname']) ? $user_detail['realname'] : '';
$user_phone = isset($user_detail['phone']) ? $user_detail['phone'] : '';
$user_email = isset($user_detail['email']) ? $user_detail['email'] : '';
$user_avatar = isset($user_detail['avatar']) ? $user_detail['avatar'] : '';
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">

<style>
    /* 确保整个页面所有元素始终可见 */
    html, body, div, span, button, input, label, form, h2, h3, p, small, i {
        opacity: 1 !important;
        visibility: visible !important;
    }

    .profile-header {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 16px;
        padding: 16px 18px;
        background: #fff;
        border: 1px solid #e8eaed;
        border-radius: 6px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        opacity: 1 !important;
        visibility: visible !important;
    }
    .avatar-preview {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 0;
        overflow: hidden;
        border: 2px solid #188038;
        flex-shrink: 0;
    }
    .avatar-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .avatar-preview i {
        font-size: 32px;
        color: #9aa0a6;
    }
    .profile-info h3 {
        margin: 0 0 6px 0;
        color: #202124;
        font-size: 16px;
        font-weight: 600;
    }
    .profile-info p {
        margin: 2px 0;
        color: #5f6368;
        font-size: 12px;
        line-height: 1.4;
    }
    .avatar-upload {
        display: flex;
        align-items: center;
        gap: 15px;
    }
    .avatar-upload input[type="file"] {
        display: none;
    }
    .avatar-upload label {
        display: inline-block;
        padding: 8px 16px;
        background: #f1f3f4;
        border-radius: 4px;
        cursor: pointer;
        font-size: 13px;
        color: #202124;
        transition: background 0.2s;
    }
    .avatar-upload label:hover {
        background: #e8eaed;
    }
    @media (max-width: 768px) {
        .profile-header {
            flex-direction: column;
            text-align: center;
            padding: 14px 16px;
        }
        .avatar-preview {
            margin-right: 0;
            margin-bottom: 10px;
        }
    }
</style>

<div class="content-area">
    <div id="alertContainer"></div>
    
    <div class="page-header">
        <h2><i class="fas fa-user"></i> <?php echo L('title', 'profile'); ?></h2>
    </div>
    
    <div class="profile-header">
        <div class="avatar-preview">
            <?php if (!empty($user_avatar)): ?>
                <img src="<?php echo htmlspecialchars($user_avatar); ?>" alt="头像">
            <?php else: ?>
                <i class="fas fa-user"></i>
            <?php endif; ?>
        </div>
        <div class="profile-info">
            <h3><?php echo htmlspecialchars($user['user']); ?></h3>
            <p><?php echo !empty($user_realname) ? htmlspecialchars($user_realname) : L('realname', 'profile') . ' ' . L('please_input', 'form'); ?></p>
            <p><?php echo !empty($user_email) ? htmlspecialchars($user_email) : L('email', 'profile') . ' ' . L('please_input', 'form'); ?></p>
        </div>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-user-circle"></i> <?php echo L('basic_info', 'profile'); ?></h3>
        <form id="profileForm">
            <div class="form-group">
                <label for="user"><?php echo L('username', 'profile'); ?></label>
                <input type="text" class="form-control" id="user" name="user" value="<?php echo htmlspecialchars($user['user']); ?>" readonly>
            </div>
            <div class="form-group">
                <label for="realname"><?php echo L('realname', 'profile'); ?></label>
                <input type="text" class="form-control" id="realname" name="realname" value="<?php echo htmlspecialchars($user_realname); ?>" placeholder="<?php echo L('please_input', 'form') . L('realname', 'profile'); ?>">
            </div>
            <div class="form-group">
                <label for="email"><?php echo L('email', 'profile'); ?></label>
                <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user_email); ?>" placeholder="<?php echo L('please_input', 'form') . L('email', 'profile'); ?>">
            </div>
            <div class="form-group">
                <label for="phone"><?php echo L('phone', 'profile'); ?></label>
                <input type="tel" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($user_phone); ?>" placeholder="<?php echo L('please_input', 'form') . L('phone', 'profile'); ?>">
                <p class="help-text"><?php echo L('please_input', 'form'); ?> <?php echo L('phone', 'profile'); ?></p>
            </div>
            <div class="form-group">
                <label><?php echo L('avatar', 'profile'); ?></label>
                <div class="avatar-upload">
                    <input type="file" id="avatar" name="avatar" accept="image/*" onchange="previewAvatar(this)">
                    <label for="avatar">
                        <i class="fas fa-upload"></i> <?php echo L('select_avatar', 'profile'); ?>
                    </label>
                    <span id="avatarFileName"><?php echo !empty($user_avatar) ? L('avatar_uploaded', 'profile') : L('no_file_selected', 'profile'); ?></span>
                </div>
                <small class="text-muted"><?php echo L('avatar_help', 'profile'); ?></small>
            </div>
            <button type="button" class="btn btn-primary" data-action="update-profile">
                <i class="fas fa-save"></i> <?php echo L('save_profile', 'profile'); ?>
            </button>
        </form>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-lock"></i> <?php echo L('change_password', 'profile'); ?></h3>
        <form id="passwordForm">
            <div class="form-group">
                <label for="oldpass"><?php echo L('old_password', 'profile'); ?></label>
                <input type="password" class="form-control" id="oldpass" name="oldpass" placeholder="<?php echo L('please_input', 'form') . L('old_password', 'profile'); ?>">
            </div>
            <div class="form-group">
                <label for="newpass"><?php echo L('new_password', 'profile'); ?></label>
                <input type="password" class="form-control" id="newpass" name="newpass" placeholder="<?php echo L('please_input', 'form') . L('new_password', 'profile'); ?>">
                <small class="text-muted"><?php echo L('password_length_error', 'profile'); ?></small>
            </div>
            <div class="form-group">
                <label for="confirmpass"><?php echo L('confirm_password', 'profile'); ?></label>
                <input type="password" class="form-control" id="confirmpass" name="confirmpass" placeholder="<?php echo L('please_input', 'form') . L('confirm_password', 'profile'); ?>">
            </div>
            <button type="button" class="btn btn-primary" data-action="change-password">
                <i class="fas fa-key"></i> <?php echo L('change_password', 'profile'); ?>
            </button>
        </form>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>

<script>
function previewAvatar(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('.avatar-preview').html('<img src="' + e.target.result + '" alt="头像">');
            $('#avatarFileName').text(input.files[0].name);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function showAlert(message, type) {
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? '<i class="fas fa-check-circle"></i> ' : '<i class="fas fa-exclamation-circle"></i> ';
    var alertHtml = '<div class="alert ' + alertClass + '">' + icon + message + '</div>';
    $('#alertContainer').html(alertHtml);
    setTimeout(function() {
        $('#alertContainer').html('');
    }, 3000);
}

function updateProfile() {
    var formData = new FormData($('#profileForm')[0]);
    formData.append('egn', 'updateprofile');
    formData.append('user_token', (function() {
        var match = document.cookie.match(/user_token=([^;]+)/);
        return match ? match[1] : '';
    })());
    var $btn = $('#profileForm .btn-primary');
    var originalText = $btn.html();
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 保存中...');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(data) {
            $btn.prop('disabled', false).html(originalText);
            if (data.code === 'success') {
                showAlert('个人资料更新成功！', 'success');
                setTimeout(function() {
                    location.reload();
                }, 1500);
            } else {
                showAlert(data.msg || '操作失败', 'error');
            }
        },
        error: function(xhr, status, error) {
            $btn.prop('disabled', false).html(originalText);
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            showAlert('操作失败，请重试', 'error');
        }
    });
}

function changePassword() {
    var oldpass = $('#oldpass').val();
    var newpass = $('#newpass').val();
    var confirmpass = $('#confirmpass').val();
    
    if (!oldpass || !newpass || !confirmpass) {
        showAlert('请填写完整的密码信息', 'error');
        return;
    }
    
    if (newpass.length < 6) {
        showAlert('新密码长度至少6位', 'error');
        return;
    }
    
    if (newpass !== confirmpass) {
        showAlert('两次输入的密码不一致', 'error');
        return;
    }
    
    var $btn = $('#passwordForm .btn-primary');
    var originalText = $btn.html();
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 修改中...');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'changepassword',
            user_token: (function() {
                var match = document.cookie.match(/user_token=([^;]+)/);
                return match ? match[1] : '';
            })(),
            oldpass: oldpass,
            newpass: newpass
        },
        dataType: 'json',
        success: function(data) {
            $btn.prop('disabled', false).html(originalText);
            if (data.code === '修改成功') {
                showAlert('密码修改成功！', 'success');
                $('#passwordForm')[0].reset();
            } else {
                showAlert(data.code, 'error');
            }
        },
        error: function(xhr, status, error) {
            $btn.prop('disabled', false).html(originalText);
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            showAlert('操作失败，请重试', 'error');
        }
    });
}

$(document).on('click', '[data-action="update-profile"]', function(e){ e.preventDefault(); updateProfile(); });
$(document).on('click', '[data-action="change-password"]', function(e){ e.preventDefault(); changePassword(); });
</script>
