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

session_start();

if (!isset($_SESSION['admin_id']) || empty($_SESSION['admin_id'])) {
    header('Location: /admin/login.php');
    exit;
}

require_once dirname(__DIR__) . '/core/db/db.php';
require_once dirname(__DIR__) . '/core/lib/license.php';

$db = \Core\Db\DB::getInstance();
$licenseObj = new \Core\Lib\License();
$licenseStatus = $licenseObj->getStatus();
$autoResetNotice = isset($_SESSION['license_auto_reset_notice']) ? $_SESSION['license_auto_reset_notice'] : null;
$remoteResetNotice = isset($_SESSION['license_remote_reset_notice']) ? $_SESSION['license_remote_reset_notice'] : null;
if ($autoResetNotice) {
    unset($_SESSION['license_auto_reset_notice']);
}
if ($remoteResetNotice) {
    unset($_SESSION['license_remote_reset_notice']);
}

$siteConfig = [];
$configs = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')}");
foreach ($configs as $cfg) {
    $siteConfig[$cfg['config_key']] = $cfg['config_value'];
}

$license = $db->fetch("SELECT * FROM {$db->table('license')} ORDER BY update_time DESC LIMIT 1");
$levelNames = ['体验版', '免费版', '基础版', '专业版'];
$currentLevel = $license ? $license['license_level'] : 0;
$licenseKey = isset($license['license_code']) ? $license['license_code'] : '';
$licenseDomain = isset($license['license_domain']) ? $license['license_domain'] : '';
$currentHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$licenseDomainMismatch = false;
if (!empty($licenseDomain) && !empty($currentHost)) {
    if ($currentLevel <= 1) {
        $licenseDomainMismatch = ($licenseDomain !== $currentHost);
    } else {
        $domains = array_map('trim', explode(',', $licenseDomain));
        $licenseDomainMismatch = !in_array($currentHost, $domains);
    }
}

// 获取未读消息数
$unreadMsg = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('message')} WHERE is_read = 0")['cnt'];

$announcementText = '芋头CMS 企业内容管理系统';
$announcementCh = curl_init();
curl_setopt($announcementCh, CURLOPT_URL, 'http://yutou.wtbidc.cn/license-center/api.php?action=announcement');
curl_setopt($announcementCh, CURLOPT_TIMEOUT, 3);
curl_setopt($announcementCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($announcementCh, CURLOPT_SSL_VERIFYPEER, false);
$announcementResp = curl_exec($announcementCh);
curl_close($announcementCh);
if ($announcementResp) {
    $annData = json_decode($announcementResp, true);
    if ($annData && isset($annData['content']) && !empty($annData['content'])) {
        $announcementText = $annData['content'];
    }
}

$currentModule = isset($_GET['act']) ? $_GET['act'] : 'dashboard';

$menus = [
    'dashboard' => ['name' => '系统概览', 'icon' => 'fa fa-th-large', 'sub' => []],
    'content' => ['name' => '内容运营', 'icon' => 'fa fa-pencil-square-o', 'sub' => [
        ['name' => '内容管理', 'url' => '/admin/main.php?act=content', 'icon' => 'fa fa-th-large'],
        ['name' => '栏目管理', 'url' => '/admin/main.php?act=channel', 'icon' => 'fa fa-sitemap'],
        ['name' => '单页管理', 'url' => '/admin/main.php?act=page', 'icon' => 'fa fa-file'],
        ['name' => '图集管理', 'url' => '/admin/main.php?act=image', 'icon' => 'fa fa-photo'],
    ]],
    'user' => ['name' => '用户与交易', 'icon' => 'fa fa-users', 'sub' => [
        ['name' => '管理员', 'url' => '/admin/main.php?act=admin_user', 'icon' => 'fa fa-user-circle'],
        ['name' => '会员列表', 'url' => '/admin/main.php?act=member', 'icon' => 'fa fa-users'],
        ['name' => '会员组别', 'url' => '/admin/main.php?act=member_group', 'icon' => 'fa fa-object-group'],
        ['name' => '站内消息', 'url' => '/admin/main.php?act=message', 'icon' => 'fa fa-bell'],
        ['name' => '产品订单', 'url' => '/admin/main.php?act=order', 'icon' => 'fa fa-shopping-cart'],
        ['name' => '充值记录', 'url' => '/admin/main.php?act=recharge', 'icon' => 'fa fa-rmb'],
    ]],
    'interact' => ['name' => '互动营销', 'icon' => 'fa fa-commenting', 'sub' => [
        ['name' => '留言板', 'url' => '/admin/main.php?act=guestbook', 'icon' => 'fa fa-comments'],
        ['name' => '评论管理', 'url' => '/admin/main.php?act=comment', 'icon' => 'fa fa-comment'],
        ['name' => '投票调查', 'url' => '/admin/main.php?act=vote', 'icon' => 'fa fa-check-square'],
        ['name' => '投稿管理', 'url' => '/admin/main.php?act=contribute', 'icon' => 'fa fa-edit'],
    ]],
    'tools' => ['name' => '推广展示', 'icon' => 'fa fa-bullhorn', 'sub' => [
        ['name' => '幻灯片', 'url' => '/admin/main.php?act=slide', 'icon' => 'fa fa-image'],
        ['name' => '友情链接', 'url' => '/admin/main.php?act=link', 'icon' => 'fa fa-link'],
        ['name' => '广告管理', 'url' => '/admin/main.php?act=ads', 'icon' => 'fa fa-ad'],
    ]],
    'system' => ['name' => '系统配置', 'icon' => 'fa fa-cog', 'sub' => [
        ['name' => '模板中心', 'url' => '/admin/main.php?act=template', 'icon' => 'fa fa-paint-brush'],
        ['name' => '使用帮助', 'url' => '/admin/main.php?act=help_center', 'icon' => 'fa fa-book'],
        ['name' => '标签帮助', 'url' => '/admin/main.php?act=tag_help', 'icon' => 'fa fa-tags'],
        ['name' => '网站设置', 'url' => '/admin/main.php?act=site', 'icon' => 'fa fa-cog'],
        ['name' => '版本管理', 'url' => '/admin/main.php?act=version', 'icon' => 'fa fa-refresh'],
        ['name' => '支付设置', 'url' => '/admin/main.php?act=payment', 'icon' => 'fa fa-money'],
        ['name' => '自定义变量', 'url' => '/admin/main.php?act=custom_var', 'icon' => 'fa fa-code'],
        ['name' => '授权信息', 'url' => '/admin/main.php?act=auth', 'icon' => 'fa fa-shield'],
        ['name' => '操作日志', 'url' => '/admin/main.php?act=log', 'icon' => 'fa fa-history'],
        ['name' => '数据库', 'url' => '/admin/main.php?act=database', 'icon' => 'fa fa-database'],
    ]],
];

$moduleMap = [];
foreach ($menus as $key => $group) {
    foreach ($group['sub'] as $sub) {
        preg_match('/act=(\w+)/', $sub['url'], $matches);
        if ($matches) {
            $moduleMap[$matches[1]] = $key;
        }
    }
}
$currentGroup = isset($moduleMap[$currentModule]) ? $moduleMap[$currentModule] : '';
$adminName = isset($_SESSION['admin_realname']) && $_SESSION['admin_realname'] !== '' ? $_SESSION['admin_realname'] : (isset($_SESSION['admin_name']) ? $_SESSION['admin_name'] : '管理员');
$adminAvatar = mb_substr($adminName, 0, 1, 'utf-8');

$groupNames = [
    'dashboard' => '系统概览',
    'content' => '内容运营',
    'user' => '用户与交易',
    'interact' => '互动营销',
    'tools' => '推广展示',
    'system' => '系统配置',
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>芋头CMS - 企业网站管理平台</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/public/css/admin-new.css">
    <style>
        body { overflow: hidden; }

        /* 兼容公共样式变量命名 */
        :root {
            --header-height: var(--header-h);
            --radius: var(--r);
            --radius-lg: var(--r-lg);
        }

        html, body, .admin-shell {
            height: 100%;
        }

        .main {
            min-width: 0;
            min-height: 0;
        }

        .content {
            min-width: 0;
            min-height: 0;
        }

        /* 侧边栏折叠 */
        .sidebar.collapsed { width: var(--sidebar-collapsed); }
        .sidebar.collapsed .sidebar-logo span,
        .sidebar.collapsed .menu-item span,
        .sidebar.collapsed .menu-section-title { display: none; }
        .sidebar.collapsed .menu-item { justify-content: center; padding: 12px 0; }
        .sidebar.collapsed .sidebar-logo { justify-content: center; }

        /* 移动端按钮 */
        .sidebar-toggle {
            display: none;
            position: fixed;
            top: 12px;
            left: 12px;
            z-index: 1001;
            width: 38px;
            height: 38px;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: var(--radius);
            font-size: 16px;
            cursor: pointer;
            align-items: center;
            justify-content: center;
        }

        /* iframe */
        .main-iframe {
            width: 100%;
            height: calc(100vh - var(--header-height) - 40px);
            border: none;
            background: transparent;
            border-radius: var(--radius-lg);
        }

        /* 面板 */
        .profile-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.4);
            z-index: 999;
        }
        .profile-overlay.active { display: block; }

        .profile-panel {
            position: fixed;
            top: 0;
            right: -420px;
            width: 420px;
            height: 100vh;
            background: #fff;
            box-shadow: -4px 0 24px rgba(0, 0, 0, 0.12);
            z-index: 1000;
            transition: right 0.35s ease;
            display: flex;
            flex-direction: column;
        }
        .profile-panel.active { right: 0; }

        .profile-header {
            padding: 18px 24px;
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }
        .profile-header h3 {
            margin: 0;
            font-size: 15px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .profile-close {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            border: none;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.15s;
        }
        .profile-close:hover { background: rgba(255,255,255,0.3); }

        .profile-body { padding: 24px; overflow-y: auto; flex: 1; }

        .profile-field { margin-bottom: 16px; }
        .profile-field label { display: block; font-size: 12px; color: var(--text-light); margin-bottom: 4px; }
        .profile-field .form-control {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            font-size: 14px;
            background: var(--white);
        }
        .profile-field .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.08);
        }
        .profile-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }

        .profile-btn {
            width: 100%;
            padding: 12px;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: var(--radius);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            margin-top: 8px;
        }
        .profile-btn:hover { background: var(--primary-hover); }

        /* 响应式 */
        @media (max-width: 1024px) {
            .sidebar-toggle { display: flex; }
            .sidebar {
                transform: translateX(-100%);
                position: fixed;
                z-index: 1000;
            }
            .sidebar.show { transform: translateX(0); }
            .sidebar-overlay {
                display: none;
                position: fixed;
                inset: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 999;
            }
            .sidebar-overlay.show { display: block; }
        }
    </style>
</head>
<body class="admin-shell">
    <button class="sidebar-toggle" onclick="toggleSidebar()">
        <i class="fa fa-bars"></i>
    </button>
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>

    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-logo">
            <i class="fa fa-cogs"></i>
            <span>芋头CMS-网站管理系统</span>
        </div>

        <div class="sidebar-menu">
            <!-- 控制台 -->
            <div class="menu-section">
                <a href="/admin/main.php?act=dashboard" class="menu-item <?php echo $currentModule === 'dashboard' ? 'active' : ''; ?>" target="mainFrame">
                    <i class="fa fa-dashboard"></i>
                    <span>控制台</span>
                </a>
            </div>

            <!-- 分组菜单（可折叠） -->
            <?php foreach (['content', 'user', 'interact', 'tools', 'system'] as $key): ?>
            <?php $group = $menus[$key]; ?>
            <?php $defaultOpen = in_array($key, ['content', 'user']); ?>
            <div class="menu-section">
                <div class="menu-group open" data-group="<?php echo $key; ?>">
                    <a href="javascript:void(0)" class="menu-item menu-group-toggle active" onclick="var g=this.parentNode, s=g.querySelector('.submenu'); g.classList.toggle('open'); s.style.display=g.classList.contains('open')?'block':'none'; return false;">
                        <i class="<?php echo $group['icon']; ?>"></i>
                        <span><?php echo $group['name']; ?></span>
                        <i class="fa fa-chevron-down menu-arrow" style="margin-left:auto;font-size:10px;"></i>
                    </a>
                    <div class="submenu" style="display:block;">
                        <?php foreach ($group['sub'] as $sub): ?>
                        <?php preg_match('/act=(\w+)/', $sub['url'], $matches); ?>
                        <a href="<?php echo $sub['url']; ?>" class="menu-item submenu-item<?php echo (isset($matches[1]) ? $matches[1] : '') === $currentModule ? ' active' : ''; ?>" target="mainFrame">
                            <i class="<?php echo $sub['icon']; ?>"></i>
                            <span><?php echo $sub['name']; ?></span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main">
        <!-- 顶部栏 -->
        <div class="header">
            <div class="header-left">
                <div class="header-breadcrumb">
                    <span class="current"><?php echo isset($groupNames[$currentGroup]) ? $groupNames[$currentGroup] : $groupNames['dashboard']; ?></span>
                </div>
            </div>
            <div class="header-right">
                <div class="announcement-bar">
                    <i class="fa fa-volume-up"></i>
                    <span><?php echo htmlspecialchars($announcementText); ?></span>
                </div>
                <a href="/admin/main.php?act=message" class="quick-license-info" title="站内消息" target="mainFrame">
                    <i class="fa fa-envelope" style="color:var(--primary);"></i>
                    <?php if ($unreadMsg > 0): ?>
                    <span class="msg-badge"><?php echo $unreadMsg; ?></span>
                    <?php endif; ?>
                </a>
                <a href="<?php echo rtrim(isset($siteConfig['site_url']) ? $siteConfig['site_url'] : 'http://' . $_SERVER['HTTP_HOST'], '/'); ?>" class="quick-license-info" title="访问主页" target="_blank">
                    <i class="fa fa-globe" style="color:var(--primary);"></i>
                    <span>访问主页</span>
                </a>
                <a href="/admin/main.php?act=auth" class="quick-license-info" title="授权信息：<?php echo $licenseDomain ?: '未激活'; ?>" target="mainFrame">
                    <i class="fa fa-shield" style="color:var(--primary);"></i>
                    <span class="quick-license-key"><?php echo $currentLevel >= 2 ? '已授权' : '未授权'; ?></span>
                </a>
                <div class="user-info" onclick="openProfilePanel()">
                    <div class="user-avatar"><?php echo $adminAvatar; ?></div>
                    <div>
                        <div class="user-name"><?php echo htmlspecialchars($adminName); ?></div>
                        <div class="user-role"><?php echo isset($levelNames[$currentLevel]) ? $levelNames[$currentLevel] : '游客'; ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 内容面板 -->
        <div class="content">
            <?php if ($autoResetNotice): ?>
            <div style="margin:12px 12px 0 12px;padding:12px 16px;border-radius:10px;background:#ecfdf5;border:1px solid #86efac;color:#166534;font-size:13px;">
                <strong>授权已自动恢复免费版：</strong> 检测到原授权域名 <?php echo htmlspecialchars($autoResetNotice['old_domain']); ?> 与当前访问域名 <?php echo htmlspecialchars($autoResetNotice['new_domain']); ?> 不匹配，系统已自动切换为当前域名免费授权。
            </div>
            <?php endif; ?>
            <?php if ($licenseDomainMismatch): ?>
            <div style="margin:12px 12px 0 12px;padding:12px 16px;border-radius:10px;background:#fff7ed;border:1px solid #fdba74;color:#9a3412;font-size:13px;">
                <strong>授权域名不匹配：</strong> 当前访问域名是 <?php echo htmlspecialchars($currentHost); ?>，本地授权绑定域名是 <?php echo htmlspecialchars($licenseDomain); ?>。
                请到“授权信息”重新激活，或清理本地授权缓存。
            </div>
            <?php endif; ?>
            <iframe name="mainFrame" src="/admin/main.php?act=<?php echo $currentModule; ?>" class="main-iframe"></iframe>
        </div>
    </div>

    <!-- 个人信息面板 -->
    <div class="profile-overlay" id="profileOverlay" onclick="closeProfilePanel()"></div>
    <div class="profile-panel" id="profilePanel">
        <div class="profile-header">
            <h3><i class="fa fa-user-circle"></i> 个人信息</h3>
            <button class="profile-close" onclick="closeProfilePanel()"><i class="fa fa-times"></i></button>
        </div>
        <div class="profile-body" id="profilePanelBody">
            <div style="text-align:center;padding:60px;color:var(--text-light);">
                <i class="fa fa-spinner fa-spin" style="font-size:28px;"></i>
            </div>
        </div>
    </div>

    <script>
    function toggleSidebar() {
        var sidebar = document.getElementById('sidebar');
        sidebar.classList.toggle('show');
        document.querySelector('.sidebar-overlay').classList.toggle('show');
    }
    function openProfilePanel() {
        document.getElementById('profileOverlay').classList.add('active');
        document.getElementById('profilePanel').classList.add('active');
        document.getElementById('profilePanelBody').innerHTML = '<div style="text-align:center;padding:60px;color:var(--text-light);"><i class="fa fa-spinner fa-spin" style="font-size:28px;"></i></div>';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/admin/main.php?act=profile&ajax=1', true);
        xhr.onload = function() { if (xhr.status === 200) { document.getElementById('profilePanelBody').innerHTML = xhr.responseText; } };
        xhr.send();
    }
    function closeProfilePanel() {
        document.getElementById('profileOverlay').classList.remove('active');
        document.getElementById('profilePanel').classList.remove('active');
    }
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeProfilePanel(); });

    // 系统更新提醒
    var updateRemind = '<?php echo isset($siteConfig['update_remind']) ? $siteConfig['update_remind'] : 'modal'; ?>';
    var localVersion = '<?php echo \Core\Lib\License::VERSION; ?>';
    if (updateRemind !== 'off') {
        var xhrUpdate = new XMLHttpRequest();
        xhrUpdate.open('GET', 'http://yutou.wtbidc.cn/license-center/api.php?action=latest_version', true);
        xhrUpdate.timeout = 5000;
        xhrUpdate.onload = function() {
            if (xhrUpdate.status === 200) {
                try {
                    var res = JSON.parse(xhrUpdate.responseText);
                    if (res.code === 200 && res.version && res.version !== localVersion) {
                        if (updateRemind === 'modal') {
                            showUpdateModal(res);
                        } else {
                            showUpdateBanner(res);
                        }
                    }
                } catch(e) {}
            }
        };
        xhrUpdate.send();
    }
    function showUpdateModal(info) {
        var overlay = document.createElement('div');
        overlay.id = 'updateModalOverlay';
        overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
        overlay.innerHTML = '<div style="background:#fff;border-radius:16px;padding:32px;max-width:400px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);">' +
            '<div style="width:64px;height:64px;background:linear-gradient(135deg,#667eea,#764ba2);border-radius:16px;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;font-size:32px;color:#fff;"><i class="fa fa-arrow-circle-up"></i></div>' +
            '<h2 style="margin:0 0 8px;font-size:20px;color:#1e293b;">发现新版本</h2>' +
            '<div style="font-size:14px;color:#64748b;margin-bottom:20px;">发现新版本 <strong style="color:#6366f1;">v' + info.version + '</strong>，您当前是 v' + localVersion + '</div>' +
            '<div style="background:#f8fafc;border-radius:8px;padding:14px;margin-bottom:20px;text-align:left;font-size:13px;color:#475569;max-height:150px;overflow-y:auto;">' + (info.changelog || '优化了系统性能和稳定性') + '</div>' +
            '<div style="display:flex;gap:12px;">' +
            '<button onclick="closeUpdateModal()" style="flex:1;padding:12px;border:1px solid #e2e8f0;background:#fff;color:#475569;border-radius:8px;cursor:pointer;font-size:14px;">稍后提醒</button>' +
            '<button onclick="location.href=\'?act=auth\'" style="flex:1;padding:12px;border:none;background:#6366f1;color:#fff;border-radius:8px;cursor:pointer;font-size:14px;">立即升级</button>' +
            '</div></div>';
        document.body.appendChild(overlay);
        overlay.addEventListener('click', function(e) { if (e.target === overlay) closeUpdateModal(); });
    }
    function closeUpdateModal() {
        var el = document.getElementById('updateModalOverlay');
        if (el) el.remove();
    }
    var updateBannerShown = false;
    function showUpdateBanner(info) {
        if (updateBannerShown) return;
        updateBannerShown = true;
        var bar = document.createElement('div');
        bar.style.cssText = 'position:fixed;bottom:0;left:0;right:0;background:linear-gradient(90deg,#667eea,#764ba2);color:#fff;padding:10px 20px;font-size:13px;z-index:9999;display:flex;align-items:center;justify-content:space-between;box-shadow:0 -4px 20px rgba(0,0,0,0.15);';
        bar.innerHTML = '<span>发现新版本 v' + info.version + '，您当前是 v' + localVersion + '</span><div style="display:flex;gap:10px;"><button onclick="this.parentElement.parentElement.remove()" style="padding:4px 12px;background:rgba(255,255,255,0.2);border:1px solid rgba(255,255,255,0.4);color:#fff;border-radius:6px;cursor:pointer;font-size:12px;">关闭</button><button onclick="location.href=\'?act=auth\'" style="padding:4px 12px;background:#fff;color:#6366f1;border:none;border-radius:6px;cursor:pointer;font-size:12px;">升级</button></div>';
        document.body.appendChild(bar);
    }
    </script>
</body>
</html>