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

// 检查登录状态
if (!isLoggedIn()) {
    redirect(SITE_URL . 'modules/home/login.php');
}

$user = currentUser();
$isAdmin = ($user['role'] === 'admin');
$isEmployee = ($user['role'] === 'employee');

$page = $_GET['page'] ?? 'dashboard';

// ========== SVG 图标配置 ==========
$svg_icons = [
    'dashboard'       => 'https://api.iconify.design/mdi:view-dashboard.svg?color=currentColor',
    'apps'            => 'https://api.iconify.design/mdi:application.svg?color=currentColor',
    'licenses'        => 'https://api.iconify.design/mdi:key.svg?color=currentColor',
    'invite'          => 'https://api.iconify.design/mdi:account-plus.svg?color=currentColor',
    'buy_app'         => 'https://api.iconify.design/mdi:cart.svg?color=currentColor',
    'buy_group'       => 'https://api.iconify.design/mdi:account-group.svg?color=currentColor',
    'recharge'        => 'https://api.iconify.design/mdi:wallet.svg?color=currentColor',
    'balance_log'     => 'https://api.iconify.design/mdi:format-list-bulleted.svg?color=currentColor',
    'tickets'         => 'https://api.iconify.design/mdi:ticket.svg?color=currentColor',
    'ticket_view'     => 'https://api.iconify.design/mdi:ticket-outline.svg?color=currentColor',
    'login_log'       => 'https://api.iconify.design/mdi:history.svg?color=currentColor',
    'profile'         => 'https://api.iconify.design/mdi:account.svg?color=currentColor',
    'changepwd'       => 'https://api.iconify.design/mdi:lock.svg?color=currentColor',
    'avatar'          => 'https://api.iconify.design/mdi:camera.svg?color=currentColor',
    'version'         => 'https://api.iconify.design/mdi:information.svg?color=currentColor',
    'agent_dashboard' => 'https://api.iconify.design/mdi:handshake.svg?color=currentColor',
    'agent_upload'    => 'https://api.iconify.design/mdi:package-variant.svg?color=currentColor',
    'downloads'       => 'https://api.iconify.design/mdi:download.svg?color=currentColor',
    'agent_apps'      => 'https://api.iconify.design/mdi:apps.svg?color=currentColor',
    'agent_orders'    => 'https://api.iconify.design/mdi:shopping.svg?color=currentColor',
    'agent_withdraw'  => 'https://api.iconify.design/mdi:cash.svg?color=currentColor',
    'agent_sell'      => 'https://api.iconify.design/mdi:link-variant.svg?color=currentColor',
    'apply_agent'     => 'https://api.iconify.design/mdi:file-document.svg?color=currentColor',
    'stats'           => 'https://api.iconify.design/mdi:chart-bar.svg?color=currentColor',
    'card_codes'      => 'https://api.iconify.design/mdi:credit-card.svg?color=currentColor',
    'user_groups'     => 'https://api.iconify.design/mdi:account-group-outline.svg?color=currentColor',
    'users'           => 'https://api.iconify.design/mdi:account-multiple.svg?color=currentColor',
    'user_detail'     => 'https://api.iconify.design/mdi:account-details.svg?color=currentColor',
    'user_balance'    => 'https://api.iconify.design/mdi:cash-multiple.svg?color=currentColor',
    'encrypt_tool'    => 'https://api.iconify.design/mdi:shield-lock.svg?color=currentColor',
    'orders'          => 'https://api.iconify.design/mdi:package.svg?color=currentColor',
    'agent_products'  => 'https://api.iconify.design/mdi:package-check.svg?color=currentColor',
    'agent_applications' => 'https://api.iconify.design/mdi:account-check.svg?color=currentColor',
    'agent_withdrawals'  => 'https://api.iconify.design/mdi:cash-check.svg?color=currentColor',
    'announcements'   => 'https://api.iconify.design/mdi:bullhorn.svg?color=currentColor',
    'links'           => 'https://api.iconify.design/mdi:link.svg?color=currentColor',
    'changelog'       => 'https://api.iconify.design/mdi:note-text.svg?color=currentColor',
    'config'          => 'https://api.iconify.design/mdi:cog.svg?color=currentColor',
    'payments'        => 'https://api.iconify.design/mdi:credit-card-outline.svg?color=currentColor',
    'updates'         => 'https://api.iconify.design/mdi:cloud-download.svg?color=currentColor',
    'update'          => 'https://api.iconify.design/mdi:cloud-download.svg?color=currentColor',
    'home'            => 'https://api.iconify.design/mdi:home.svg?color=currentColor',
    'logout'          => 'https://api.iconify.design/mdi:logout.svg?color=currentColor',
    'default'         => 'https://api.iconify.design/mdi:circle.svg?color=currentColor',
    'celebration'     => 'https://api.iconify.design/mdi:party-popper.svg?color=%23667eea',
    'resources'       => 'https://api.iconify.design/mdi:package-variant.svg?color=%23667eea',
    'login'           => 'https://api.iconify.design/mdi:login.svg?color=currentColor',
    'mail'            => 'https://api.iconify.design/mdi:email.svg?color=currentColor',
    'chevron-down'    => 'https://api.iconify.design/mdi:chevron-down.svg?color=currentColor',
    'chevron-right'   => 'https://api.iconify.design/mdi:chevron-right.svg?color=currentColor',
];

// 用户菜单分组
$userMenuGroups = [
    'dashboard' => [
        'title' => '用户中心',
        'icon' => 'dashboard',
        'pages' => [
            'dashboard' => '用户中心',
            'bind_wechat' =>'绑定微信',
            'notifications'=>'信息中心',


        ]
    ],
    'apps' => [
        'title' => '应用与授权',
        'icon' => 'licenses',
        'pages' => [
            'apps' => '我的应用',
            'licenses' => '授权码管理',
            'buy_app' => '购买授权',
        ]
    ],
    'finance' => [
        'title' => '财务管理',
        'icon' => 'recharge',
        'pages' => [
            'buy_group' => '购买会员',
            'recharge' => '余额充值',
            'balance_log' => '余额明细',
        ]
    ],
    'tickets' => [
        'title' => '客服工单',
        'icon' => 'tickets',
        'pages' => [
            'tickets' => '工单系统',
            'ticket_view' => '工单详情',
        ]
    ],
    'account' => [
        'title' => '账户设置',
        'icon' => 'config',
        'pages' => [
            'profile' => '个人资料',
            'changepwd' => '修改密码',
            'avatar' => '上传头像',
            'version' => '版本信息',
        ]
    ],
];

// 管理员菜单分组
$adminMenuGroups = [
    'dashboard' => [
        'title' => '控制台',
        'icon' => 'dashboard',
        'pages' => [
            'dashboard' => '控制台',
            'stats' => '数据统计',
            'notifications'=>'信息中心',

        ]
    ],
    'users' => [
        'title' => '用户管理',
        'icon' => 'users',
        'pages' => [
            'users' => '用户列表',
            'user_groups' => '会员组管理',
        ]
    ],
    'apps' => [
        'title' => '应用与授权',
        'icon' => 'licenses',
        'pages' => [
            'apps' => '应用管理',
            'licenses' => '授权管理',
            'card_codes' => '卡密管理',
        ]
    ],
    'orders' => [
        'title' => '交易管理',
        'icon' => 'orders',
        'pages' => [
            'orders' => '订单管理',
        ]
    ],
    'tickets' => [
        'title' => '客服工单',
        'icon' => 'tickets',
        'pages' => [
            'tickets' => '工单管理',
        ]
    ],
    'content' => [
    'title' => '内容管理',
    'icon' => 'announcements',
    'pages' => [
        'announcements' => '公告管理',
        'admin_notifications' => '站内信管理',
        'links' => '链接管理',
        'downloads' => '资源下载(用户用)',
        'resources' => '资源下载(站长用)',
    ]
],
    'system' => [
        'title' => '系统设置',
        'icon' => 'config',
        'pages' => [
            'config' => '网站配置',
            'mail_config' => '邮箱配置',
            'mail_template' => '邮件模板',
            'quick_login' => '快捷登录',
            'update' => '系统更新',
        ]
    ],
];

if ($isAdmin) {
    $allowedPages = [];
    foreach ($adminMenuGroups as $group) {
        $allowedPages = array_merge($allowedPages, $group['pages']);
    }
    // 添加隐藏页面（不在菜单显示但需要访问）
    $allowedPages['user_detail'] = '用户详情';
    $allowedPages['user_balance'] = '用户余额明细';
    $allowedPages['notification_detail'] = '信息详情';
    $allowedPages['ticket_view'] = '工单详情';
    $allowedPages['quick_login_config'] = '登录配置';
    $allowedPages['resources'] = '资源下载';
} elseif ($isEmployee) {
    $allowedPages = ['dashboard' => '控制台'];
    if (hasPermission('apps.view')) {
        $allowedPages['apps'] = '应用管理';
    }
    if (hasPermission('users.view')) {
        $allowedPages['users'] = '用户管理';
    }
    if (hasPermission('orders.view')) {
        $allowedPages['orders'] = '订单管理';
    }
    if (hasPermission('tickets.handle')) {
        $allowedPages['tickets'] = '工单管理';
    }
} else {
    $allowedPages = [];
    foreach ($userMenuGroups as $group) {
        $allowedPages = array_merge($allowedPages, $group['pages']);
    }
    // 添加隐藏页面
    $allowedPages['ticket_view'] = '工单详情';
    $allowedPages['notification_detail'] = '信息详情';
}

if (!isset($allowedPages[$page])) $page = 'dashboard';

$pageFile = ($isAdmin || $isEmployee) ? __DIR__ . '/modules/admin/' . $page . '.php' : __DIR__ . '/modules/user/' . $page . '.php';
if (!file_exists($pageFile)) $pageFile = __DIR__ . '/modules/user/dashboard.php';

$siteConfig = getSiteConfig();
$headerLinks = getHeaderLinks();
$friendLinks = getFriendLinks();

function getPageIcon($page) {
    global $svg_icons;
    $iconMap = [
        'dashboard' => 'dashboard', 'apps' => 'apps', 'licenses' => 'licenses',
        'buy_app' => 'buy_app', 'buy_group' => 'buy_group', 'recharge' => 'recharge',
        'balance_log' => 'balance_log', 'tickets' => 'tickets', 'ticket_view' => 'ticket_view',
        'profile' => 'profile', 'changepwd' => 'changepwd', 'avatar' => 'avatar',
        'user_groups' => 'user_groups', 'users' => 'users', 'orders' => 'orders',
        'config' => 'config', 'links' => 'links', 'updates' => 'updates', 'update' => 'update',
        'payments' => 'payments', 'downloads' => 'downloads', 'version' => 'version',
        'changelog' => 'changelog', 'agent_sell' => 'agent_sell',
        'agent_withdrawals' => 'agent_withdrawals', 'user_detail' => 'user_detail',
        'user_balance' => 'user_balance', 'agent_dashboard' => 'agent_dashboard',
        'agent_apps' => 'agent_apps', 'agent_orders' => 'agent_orders',
        'agent_withdraw' => 'agent_withdraw', 'apply_agent' => 'apply_agent',
        'agent_applications' => 'agent_applications', 'announcements' => 'announcements',
        'encrypt_tool' => 'encrypt_tool', 'stats' => 'stats', 'card_codes' => 'card_codes',
        'agent_products' => 'agent_products', 'invite' => 'invite', 'login_log' => 'login_log',
        'resources'=>'resources', 'quick_login_config'=>'login', 'quick_login'=>'login',
        'mail_template'=>'mail', 'mail_config'=>'mail','bind_wechat'=>'dashboard'
    ];
    $iconKey = $iconMap[$page] ?? 'default';
    return $svg_icons[$iconKey] ?? $svg_icons['default'];
}

// 从 localStorage 读取菜单展开状态
$expandedGroups = isset($_COOKIE['menu_expanded']) ? explode(',', $_COOKIE['menu_expanded']) : ['dashboard'];
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title><?php echo htmlspecialchars($allowedPages[$page] ?? '用户中心'); ?> - <?php echo htmlspecialchars($siteConfig['site_name'] ?? '麟泓授权系统'); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="icon" href="/assets/uploads/favicon.ico"> 
    <script src="/assets/js/main.js" defer></script>
    <script src="/assets/js/admin.js" defer></script>
    <script src="/assets/js/qrcode.min.js"></script>
    <script src="/assets/js/chart.umd.min.js"></script>
    <script src="/assets/js/jquery.min.js"></script>
    <style>
    /* 侧边栏样式 */
    .sidebar {
        padding-top: 0;
        position: fixed;
        left: 0;
        top: 0;
        height: 100vh;
        z-index: 100;
        overflow-y: auto;
        width: 260px;
        background: var(--bg-primary);
        border-right: 1px solid var(--border-color);
    }
    
    .sidebar-nav {
        margin-top: 0;
        padding: 16px 8px;
    }
    
    /* 菜单分组 */
    .menu-group {
        margin-bottom: 4px;
    }
    
    .menu-group-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        cursor: pointer;
        border-radius: 10px;
        color: var(--text-primary);
        font-weight: 500;
        transition: all 0.2s;
    }
    
    .menu-group-header:hover {
        background: var(--bg-secondary);
    }
    
    .menu-group-header .group-title {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    
    .menu-group-header .group-icon {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .menu-group-header .group-icon img {
        width: 20px;
        height: 20px;
        filter: brightness(0) saturate(100%);
    }
    
    .menu-group-header .chevron {
        width: 20px;
        height: 20px;
        transition: transform 0.2s;
    }
    
    .menu-group-header .chevron img {
        width: 16px;
        height: 16px;
        filter: brightness(0) saturate(100%);
    }
    
    .menu-group.expanded .menu-group-header .chevron {
        transform: rotate(90deg);
    }
    
    .menu-group-items {
        display: none;
        padding-left: 12px;
        margin-top: 4px;
    }
    
    .menu-group.expanded .menu-group-items {
        display: block;
    }
    
    .sidebar-link {
        display: flex;
        align-items: center;
        padding: 10px 16px 10px 20px;
        border-radius: 10px;
        color: var(--text-secondary);
        text-decoration: none;
        transition: all 0.2s;
        margin-bottom: 2px;
    }
    
    .sidebar-link:hover {
        background: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .sidebar-link.active {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
    }
    
    .sidebar-link .link-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        margin-right: 12px;
    }
    
    .sidebar-link .link-icon img {
        width: 18px;
        height: 18px;
        filter: brightness(0) saturate(100%);
    }
    
    .sidebar-link.active .link-icon img {
        filter: brightness(0) invert(1);
    }
    
    .sidebar-divider {
        height: 1px;
        background: var(--border-color);
        margin: 16px 8px;
    }
    
    /* 主内容区域 */
    .main-content {
        margin-left: 260px;
        display: flex;
        flex-direction: column;
        min-height: 100vh;
    }
    
    .sidebar.collapsed {
        width: 80px;
    }
    
    .sidebar.collapsed .menu-group-header .group-title span,
    .sidebar.collapsed .menu-group-header .chevron,
    .sidebar.collapsed .menu-group-items,
    .sidebar.collapsed .sidebar-link .link-text {
        display: none;
    }
    
    .sidebar.collapsed .menu-group-header {
        justify-content: center;
        padding: 12px 8px;
    }
    
    .sidebar.collapsed .sidebar-link {
        justify-content: center;
        padding: 12px 8px;
    }
    
    .sidebar.collapsed .sidebar-link .link-icon {
        margin-right: 0;
    }
    
    .sidebar.collapsed ~ .main-content {
        margin-left: 80px;
    }
    
    /* 顶部栏 */
    .top-bar-left {
        display: flex;
        align-items: center;
        padding: 16px 24px;
        border-bottom: 1px solid var(--border-color);
        background: var(--bg-primary);
        position: sticky;
        top: 0;
        z-index: 50;
    }
    
    .mobile-menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: var(--text-primary);
        padding: 8px;
        border-radius: var(--radius-sm);
        transition: background 0.2s;
    }
    
    .mobile-menu-toggle:hover {
        background: var(--bg-secondary);
    }
    
    .content-area {
        flex: 1;
        padding: 24px;
    }
    
    .footer {
        margin-top: auto;
        padding: 24px;
        border-top: 1px solid var(--border-color);
        background: var(--bg-primary);
    }
    
    /* 移动端适配 */
    @media (max-width: 768px) {
        .main-content {
            margin-left: 0;
        }
        
        .sidebar.collapsed ~ .main-content {
            margin-left: 0;
        }
        
        .sidebar {
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            width: 260px;
        }
        
        .sidebar.collapsed {
            width: 260px;
        }
        
        .sidebar.show {
            transform: translateX(0);
        }
        
        .sidebar.collapsed .menu-group-header .group-title span,
        .sidebar.collapsed .menu-group-header .chevron,
        .sidebar.collapsed .menu-group-items,
        .sidebar.collapsed .sidebar-link .link-text {
            display: inline;
        }
        
        .sidebar.collapsed .menu-group-header {
            justify-content: space-between;
            padding: 12px 16px;
        }
        
        .sidebar.collapsed .sidebar-link {
            justify-content: flex-start;
            padding: 10px 16px 10px 20px;
        }
        
        .sidebar.collapsed .sidebar-link .link-icon {
            margin-right: 12px;
        }
        
        .mobile-menu-toggle {
            display: block;
        }
        
        .top-bar-left {
            padding: 12px 16px;
        }
        
        .content-area {
            padding: 16px;
        }
    }
    </style>
</head>

<body>
    <div class="app-wrapper">
        <aside class="sidebar" id="sidebar">
           <div class="sidebar-logo">
    <a href="/" class="sidebar-logo-link">
        <img src="<?php echo htmlspecialchars($siteConfig['site_sidebar_icon'] ?? $siteConfig['site_logo'] ?? '/assets/uploads/logo.png'); ?>" alt="Logo">
        <span class="sidebar-logo-text"><?php echo htmlspecialchars($siteConfig['site_name'] ?? '麟泓授权系统'); ?></span>
    </a>
</div>
            <nav class="sidebar-nav">
                <?php if ($isAdmin): ?>
                    <!-- 管理员菜单：分组折叠 -->
                    <?php foreach ($adminMenuGroups as $groupKey => $group): ?>
                        <div class="menu-group <?php echo in_array($groupKey, $expandedGroups) ? 'expanded' : ''; ?>" data-group="<?php echo $groupKey; ?>">
                            <div class="menu-group-header" onclick="toggleMenuGroup('<?php echo $groupKey; ?>')">
                                <span class="group-title">
                                    <span class="group-icon">
                                        <img src="<?php echo $svg_icons[$group['icon']] ?? $svg_icons['default']; ?>" alt="">
                                    </span>
                                    <span><?php echo $group['title']; ?></span>
                                </span>
                                <span class="chevron">
                                    <img src="<?php echo $svg_icons['chevron-right']; ?>" alt="">
                                </span>
                            </div>
                            <div class="menu-group-items">
                                <?php foreach ($group['pages'] as $key => $title): ?>
                                    <a href="?page=<?php echo $key; ?>" class="sidebar-link <?php echo $page == $key ? 'active' : ''; ?>">
                                        <span class="link-icon">
                                            <img src="<?php echo getPageIcon($key); ?>" alt="">
                                        </span>
                                        <span class="link-text"><?php echo htmlspecialchars($title); ?></span>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
    <!-- 普通用户/员工菜单：分组折叠 -->
    <?php foreach ($userMenuGroups as $groupKey => $group): ?>
        <div class="menu-group <?php echo in_array($groupKey, $expandedGroups) ? 'expanded' : ''; ?>" data-group="<?php echo $groupKey; ?>">
            <div class="menu-group-header" onclick="toggleMenuGroup('<?php echo $groupKey; ?>')">
                <span class="group-title">
                    <span class="group-icon">
                        <img src="<?php echo $svg_icons[$group['icon']] ?? $svg_icons['default']; ?>" alt="">
                    </span>
                    <span><?php echo $group['title']; ?></span>
                </span>
                <span class="chevron">
                    <img src="<?php echo $svg_icons['chevron-right']; ?>" alt="">
                </span>
            </div>
            <div class="menu-group-items">
                <?php foreach ($group['pages'] as $key => $title): ?>
                    <?php if (isset($allowedPages[$key])): ?>
                        <a href="?page=<?php echo $key; ?>" class="sidebar-link <?php echo $page == $key ? 'active' : ''; ?>">
                            <span class="link-icon">
                                <img src="<?php echo getPageIcon($key); ?>" alt="">
                            </span>
                            <span class="link-text"><?php echo htmlspecialchars($title); ?></span>
                        </a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endforeach; ?>
                <?php endif; ?>
                
                <div class="sidebar-divider">
                </div>
                 
                <a href="/" class="sidebar-link">
                    <span class="link-icon">
                        <img src="<?php echo $svg_icons['home']; ?>" alt="">
                    </span>
                    <span class="link-text">返回首页</span>
                </a>
                <!-- ========== 用户信息卡片（新增） ========== -->
        <div class="sidebar-user-card">
            <div class="user-avatar">
                <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar" onerror="this.src='/assets/uploads/default_avatar.png'">
            </div>
            <div class="user-info">
                <span class="user-name"><?php echo htmlspecialchars($user['username'] ?? '用户'); ?></span>
                <span class="user-role">
                    <?php 
                    if ($user['role'] == 'admin') {
                        echo '管理员';
                    } elseif ($user['role'] == 'employee') {
                        echo '员工';
                    } else {
                        echo '普通用户';
                    }
                    ?>
                </span>
            </div>
            
        </div>
        <!-- ========== 用户信息卡片结束 ========== -->
                <a href="/modules/home/logout.php" class="sidebar-link logout-link">
                    <span class="link-icon">
                        <img src="<?php echo $svg_icons['logout']; ?>" alt="">
                    </span>
                    <span class="link-text">退出登录</span>
                </a>
            </nav>
        </aside>
        <main class="main-content">
            <div class="top-bar">
                <div class="top-bar-left">
                    <button class="mobile-menu-toggle" id="mobileMenuToggle" onclick="document.getElementById('sidebar').classList.toggle('show')">
                        <img src="https://api.iconify.design/mdi:menu.svg?color=currentColor" width="24" height="24" alt="">
                    </button>
                    <a href="/" class="top-bar-logo">
                        <img src="<?php echo htmlspecialchars($siteConfig['site_logo'] ?? '/assets/uploads/logo.png'); ?>" alt="Logo">
                    </a>
                </div>
                
            </div>
            <div class="content-area">
                <?php include $pageFile; ?>
            </div>
            <footer class="footer">
                <div class="footer-logo">
                    <img src="<?php echo htmlspecialchars($siteConfig['site_logo'] ?? '/assets/uploads/logo.png'); ?>" alt="Logo">
                </div>
                <div class="footer-links">
                    <?php foreach ($friendLinks as $link): ?>
                        <a href="<?php echo htmlspecialchars($link['url']); ?>" target="_blank"><?php echo htmlspecialchars($link['name']); ?></a>
                    <?php endforeach; ?>
                </div>
                <div class="footer-copyright">
                    <?php echo htmlspecialchars($siteConfig['site_copyright'] ?? ''); ?>
                    <?php if (!empty($siteConfig['site_icp'])): ?>
                        <a href="https://beian.miit.gov.cn/" target="_blank"><?php echo htmlspecialchars($siteConfig['site_icp']); ?></a>
                    <?php endif; ?>
                </div>
            </footer>
        </main>
    </div>
<script>
    const sidebar = document.getElementById('sidebar');
    const mobileMenuToggle = document.getElementById('mobileMenuToggle');
    
    const sidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    if (sidebarCollapsed && sidebar) {
        sidebar.classList.add('collapsed');
    }
    
    if (mobileMenuToggle) {
        mobileMenuToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            sidebar.classList.toggle('show');
        });
    }
    
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.addEventListener('click', function() {
            if (window.innerWidth <= 768 && sidebar.classList.contains('show')) {
                sidebar.classList.remove('show');
            }
        });
    }
    
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768 && sidebar.classList.contains('show')) {
            sidebar.classList.remove('show');
        }
    });
    
    // 菜单分组折叠功能
    function toggleMenuGroup(groupKey) {
        const group = document.querySelector(`.menu-group[data-group="${groupKey}"]`);
        if (!group) return;
        
        group.classList.toggle('expanded');
        
        // 保存展开状态到 Cookie
        const expandedGroups = [];
        document.querySelectorAll('.menu-group.expanded').forEach(g => {
            expandedGroups.push(g.dataset.group);
        });
        document.cookie = `menu_expanded=${expandedGroups.join(',')}; path=/; max-age=31536000`;
    }
    
    // 自动展开包含当前页面的分组
    document.addEventListener('DOMContentLoaded', function() {
        const currentPage = '<?php echo $page; ?>';
        const activeLink = document.querySelector(`.sidebar-link[href="?page=${currentPage}"]`);
        if (activeLink) {
            const parentGroup = activeLink.closest('.menu-group');
            if (parentGroup && !parentGroup.classList.contains('expanded')) {
                parentGroup.classList.add('expanded');
            }
        }
    });
</script>

<!-- 版本更新提醒弹窗 -->
<div id="versionUpdateModal" class="version-update-modal" style="display: none;">
    <div class="version-update-content">
        <div class="version-update-header">
            <div class="update-icon">
                <img src="<?php echo $svg_icons['celebration']; ?>" style="width:48px;height:48px;" alt="">
            </div>
            <h2>发现新版本</h2>
            <button class="close-btn" id="closeVersionModal">&times;</button>
        </div>
        <div class="version-update-body">
            <div class="version-badge">
                新版本 <span id="newVersion"></span>
            </div>
            <div class="update-date">
                发布日期：<span id="updateDate"></span>
            </div>
            <div class="update-description">
                <h4>更新内容：</h4>
                <div id="releaseNotes" class="release-notes"></div>
            </div>
        </div>
        <div class="version-update-footer">
            <button class="btn btn-secondary" id="remindLaterBtn">稍后提醒</button>
            <button class="btn btn-primary" id="viewChangelogBtn">查看完整更新日志</button>
        </div>
    </div>
</div>

<style>
/* 侧边栏 Logo */
.sidebar-logo {
    padding: 20px 16px 16px;
    border-bottom: 1px solid var(--border-color);
    margin-bottom: 8px;
}

.sidebar-logo-link {
    display: flex;
    align-items: center;
    gap: 12px;
    text-decoration: none;
}

.sidebar-logo-link img {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    object-fit: cover;
}

.sidebar-logo-text {
    font-size: 16px;
    font-weight: 700;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 侧边栏折叠状态下的 Logo */
.sidebar.collapsed .sidebar-logo {
    padding: 20px 8px 16px;
}

.sidebar.collapsed .sidebar-logo-link {
    justify-content: center;
}

.sidebar.collapsed .sidebar-logo-text {
    display: none;
}

.sidebar.collapsed .sidebar-logo-link img {
    width: 36px;
    height: 36px;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .sidebar.collapsed .sidebar-logo {
        padding: 20px 16px 16px;
    }
    
    .sidebar.collapsed .sidebar-logo-link {
        justify-content: flex-start;
    }
    
    .sidebar.collapsed .sidebar-logo-text {
        display: block;
    }
}
/* 侧边栏用户卡片 */
.sidebar-user-card {
    display: flex;
    align-items: center;
    padding: 16px 12px;
    margin: 8px;
    background: var(--bg-secondary);
    border-radius: 14px;
    border: 1px solid var(--border-color);
}

.sidebar-user-card .user-avatar {
    width: 44px;
    height: 44px;
    border-radius: 12px;
    overflow: hidden;
    margin-right: 12px;
    flex-shrink: 0;
}

.sidebar-user-card .user-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.sidebar-user-card .user-info {
    flex: 1;
    min-width: 0;
}

.sidebar-user-card .user-name {
    display: block;
    font-weight: 600;
    color: var(--text-primary);
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.sidebar-user-card .user-role {
    display: block;
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 2px;
}

.sidebar-user-card .user-actions {
    display: flex;
    gap: 4px;
    margin-left: 8px;
}

.sidebar-user-card .user-action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: var(--bg-primary);
    transition: all 0.2s;
}

.sidebar-user-card .user-action-btn:hover {
    background: var(--primary-color);
}

.sidebar-user-card .user-action-btn:hover img {
    filter: brightness(0) invert(1);
}

.sidebar-user-card .user-action-btn img {
    width: 16px;
    height: 16px;
}

/* 侧边栏折叠状态下的用户卡片 */
.sidebar.collapsed .sidebar-user-card {
    flex-direction: column;
    padding: 12px 8px;
}

.sidebar.collapsed .sidebar-user-card .user-avatar {
    margin-right: 0;
    margin-bottom: 8px;
    width: 40px;
    height: 40px;
}

.sidebar.collapsed .sidebar-user-card .user-info,
.sidebar.collapsed .sidebar-user-card .user-actions {
    display: none;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .sidebar.collapsed .sidebar-user-card {
        flex-direction: row;
        padding: 16px 12px;
    }
    
    .sidebar.collapsed .sidebar-user-card .user-avatar {
        margin-right: 12px;
        margin-bottom: 0;
        width: 44px;
        height: 44px;
    }
    
    .sidebar.collapsed .sidebar-user-card .user-info,
    .sidebar.collapsed .sidebar-user-card .user-actions {
        display: flex;
    }
}
.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-primary);
    position: sticky;
    top: 0;
    z-index: 50;
}

.top-bar-logo {
    display: flex;
    align-items: center;
    gap: 10px;
    text-decoration: none;
    margin-left: 16px;
}

.top-bar-logo img {
    height: 32px;
    width: auto;
}

.top-bar-logo span {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
}

.top-bar-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.user-info-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: 30px;
    cursor: pointer;
    font-size: 14px;
    color: var(--text-primary);
    transition: all 0.2s;
}

.user-info-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
}

.user-dropdown-menu {
    position: absolute;
    top: 100%;
    right: 24px;
    margin-top: 8px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-md);
    min-width: 180px;
    z-index: 100;
}

.user-dropdown-menu a {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 16px;
    color: var(--text-primary);
    text-decoration: none;
    transition: background 0.2s;
}

.user-dropdown-menu a:hover {
    background: var(--bg-secondary);
}

.user-dropdown-menu hr {
    margin: 4px 0;
    border: none;
    border-top: 1px solid var(--border-color);
}

@media (max-width: 768px) {
    .top-bar {
        padding: 8px 16px;
    }
    .top-bar-logo span {
        display: none;
    }
    .user-info-btn span {
        display: none;
    }
    .user-dropdown-menu {
        right: 16px;
    }
}

.version-update-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.6);
    backdrop-filter: blur(8px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10002;
    animation: fadeIn 0.3s ease;
}
.version-update-content {
    background: var(--bg-primary);
    border-radius: 24px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
    animation: slideUp 0.4s ease;
}
.version-update-header {
    padding: 24px 24px 16px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 12px;
    position: relative;
}
.version-update-header h2 {
    flex: 1;
    margin: 0;
    font-size: 24px;
}
.version-update-header .close-btn {
    background: none;
    border: none;
    font-size: 28px;
    cursor: pointer;
    color: var(--text-muted);
    line-height: 1;
}
.version-update-body {
    padding: 24px;
}
.version-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: inline-block;
    padding: 6px 16px;
    border-radius: 30px;
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 16px;
}
.update-date {
    color: var(--text-muted);
    font-size: 13px;
    margin-bottom: 20px;
}
.update-description h4 {
    margin-bottom: 12px;
    font-size: 16px;
}
.release-notes {
    background: var(--bg-secondary);
    border-radius: 12px;
    padding: 16px;
    font-size: 14px;
    line-height: 1.6;
    color: var(--text-secondary);
    white-space: pre-wrap;
}
.version-update-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    border-top: 1px solid var(--border-color);
}
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
@keyframes slideUp {
    from { transform: translateY(30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}
</style>

<script>
function checkVersionUpdate() {
    const userRole = '<?php echo $user['role'] ?? 'user'; ?>';
    const currentVersion = '<?php echo SYS_VERSION; ?>';
    
    if (userRole === 'admin') {
        return;
    }
    
    fetch('/api/get_latest_version.php')
        .then(res => res.json())
        .then(data => {
            if (data.success && data.version !== currentVersion) {
                fetch(`/api/check_version_reminded.php?version=${data.version}`)
                    .then(res => res.json())
                    .then(remindData => {
                        if (!remindData.reminded) {
                            showVersionModal(data);
                        }
                    });
            }
        })
        .catch(err => console.error('检查版本更新失败:', err));
}

function showVersionModal(versionData) {
    const userRole = '<?php echo $user['role'] ?? 'user'; ?>';
    if (userRole === 'admin') return;
    
    const modal = document.getElementById('versionUpdateModal');
    if (!modal) return;
    
    document.getElementById('newVersion').innerText = versionData.version;
    document.getElementById('updateDate').innerText = versionData.created_at || '刚刚';
    
    let notes = versionData.release_notes || '暂无更新说明';
    notes = notes.replace(/\n/g, '<br>');
    document.getElementById('releaseNotes').innerHTML = notes;
    
    modal.style.display = 'flex';
    
    fetch('/api/mark_version_reminded.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `version=${versionData.version}`
    });
}

document.getElementById('closeVersionModal')?.addEventListener('click', function() {
    document.getElementById('versionUpdateModal').style.display = 'none';
});

document.getElementById('remindLaterBtn')?.addEventListener('click', function() {
    document.getElementById('versionUpdateModal').style.display = 'none';
});

document.getElementById('viewChangelogBtn')?.addEventListener('click', function() {
    window.location.href = '?page=version';
});

document.getElementById('versionUpdateModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        this.style.display = 'none';
    }
});

document.addEventListener('DOMContentLoaded', function() {
    checkVersionUpdate();
});
</script>

<script>
$(document).ready(function() {
    var lastCheck = localStorage.getItem('update_check_date');
    var today = new Date().toDateString();
    
    if (lastCheck !== today) {
        $.ajax({
            url: '/update_api/check_update.php',
            method: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.has_update) {
                    localStorage.setItem('update_check_date', today);
                    
                    if (res.is_force) {
                        alert('强制更新：' + res.version + '，请立即更新！');
                        window.location.href = 'admin.php?page=update';
                    } else {
                        if (confirm('发现新版本 ' + res.version + '\n\n' + (res.title || '') + '\n' + (res.description || '') + '\n\n是否立即更新？')) {
                            window.location.href = 'admin.php?page=update';
                        }
                    }
                }
            }
        });
    }
});

const userDropdownBtn = document.getElementById('userDropdownBtn');
const userDropdownMenu = document.getElementById('userDropdownMenu');

if (userDropdownBtn && userDropdownMenu) {
    userDropdownBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        userDropdownMenu.style.display = userDropdownMenu.style.display === 'none' ? 'block' : 'none';
    });
    
    document.addEventListener('click', function() {
        userDropdownMenu.style.display = 'none';
    });
    
    userDropdownMenu.addEventListener('click', function(e) {
        e.stopPropagation();
    });
}
</script>
</body>
</html>