<?php
require_once __DIR__ . '/header.php';
$pdo = db();
$admin_id = $_SESSION['admin_user']['id'];

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nickname = $_POST['nickname'];
    $password = $_POST['password'];

    try {
        if (!empty($password)) {
            $stmt = $pdo->prepare("UPDATE admin_users SET nickname=?, password=? WHERE id=?");
            $stmt->execute([$nickname, password_hash($password, PASSWORD_DEFAULT), $admin_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE admin_users SET nickname=? WHERE id=?");
            $stmt->execute([$nickname, $admin_id]);
        }
        
        // Update session
        $_SESSION['admin_user']['nickname'] = $nickname;
        $msg = '<div class="alert alert-success">个人资料已更新</div>';
    } catch (Exception $e) {
        $msg = '<div class="alert alert-danger">更新失败: ' . $e->getMessage() . '</div>';
    }
}

// Re-fetch current data
$stmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->execute([$admin_id]);
$current_admin = $stmt->fetch();
?>

<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">个人资料设置</div>
            <div class="card-body">
                <?= $msg ?>
                <form method="POST">
                    <div class="mb-3 text-center">
                        <img src="../<?= htmlspecialchars($site_logo) ?>" alt="Avatar" width="100" height="100" class="rounded-circle border mb-3">
                        <div>
                            <span class="badge bg-secondary"><?= htmlspecialchars($current_admin['username']) ?></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">用户名 (不可修改)</label>
                        <input type="text" class="form-control" value="<?= htmlspecialchars($current_admin['username']) ?>" readonly disabled>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">昵称</label>
                        <input type="text" name="nickname" class="form-control" value="<?= htmlspecialchars($current_admin['nickname']) ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">新密码 (留空不修改)</label>
                        <input type="password" name="password" class="form-control" placeholder="请输入新密码">
                    </div>
                    
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
