<?php
ob_start();
require_once '../config.php';

// 检查登录
if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$user = currentUser();
$isAdmin = ($user['role'] === 'admin');
$site_name = getSiteConfig('site_name') ?? '麟泓授权';

// 获取当前页面
$page = $_GET['page'] ?? 'dashboard';

// ========== 管理员菜单 ==========
$admin_pages = [
    'dashboard' => ['name' => '控制台', 'icon' => 'view-dashboard'],
    'users' => ['name' => '用户列表', 'icon' => 'account-group'],
    'apps' => ['name' => '应用管理', 'icon' => 'application'],
    'card_codes' => ['name' => '卡密管理', 'icon' => 'credit-card'],
    'orders' => ['name' => '订单管理', 'icon' => 'package'],
    'tickets' => ['name' => '工单管理', 'icon' => 'ticket'],
    'announcements' => ['name' => '公告管理', 'icon' => 'bullhorn'],
    'resources' => ['name' => '资源下载', 'icon' => 'download'],
    'update' => ['name' => '系统更新', 'icon' => 'cloud-download'],
];

// ========== 用户菜单 ==========
$user_pages = [
    'dashboard' => ['name' => '用户中心', 'icon' => 'view-dashboard'],
    'licenses' => ['name' => '授权码管理', 'icon' => 'key'],
    'buy_app' => ['name' => '购买授权', 'icon' => 'cart'],
    'recharge' => ['name' => '余额充值', 'icon' => 'wallet'],
    'buy_group' => ['name' => '购买会员', 'icon' => 'account-group'],
    'tickets' => ['name' => '工单系统', 'icon' => 'ticket'],
    'version' => ['name' => '版本信息', 'icon' => 'information'],
];

$allowed_pages = $isAdmin ? $admin_pages : $user_pages;

// 验证页面权限
$special_pages = ['ticket_view', 'user_detail'];if (!isset($allowed_pages[$page]) && !in_array($page, $special_pages)) {
    $page = 'dashboard';
}

$page_title = $allowed_pages[$page]['name'] ?? '工单详情';

// $page_title = $allowed_pages[$page]['name'];

// 特殊页面处理（不在菜单显示）
if ($page == 'ticket_view') {
    $page_file = __DIR__ . '/' . ($isAdmin ? 'admin' : 'user') . '/ticket_view.php';
    $page_title = '工单详情';
} elseif ($page == 'user_detail') {
    $page_file = __DIR__ . '/admin/user_detail.php';
    $page_title = '用户详情';
} else {
    $page_file = __DIR__ . '/' . ($isAdmin ? 'admin' : 'user') . '/' . $page . '.php';
}

// 获取底部导航菜单（前4个）
$bottom_nav = array_slice($allowed_pages, 0, 4, true);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title><?php echo $page_title; ?> - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            padding-bottom: 75px;
        }
        
        /* 顶部导航 */
        .mobile-header {
            position: sticky;
            top: 0;
            z-index: 100;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .mobile-header .menu-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.15);
            border-radius: 50%;
            border: none;
            color: white;
            cursor: pointer;
        }
        .mobile-header .header-title {
            flex: 1;
            font-size: 18px;
            font-weight: 600;
            text-align: center;
        }
        .mobile-header .scan-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.15);
            border-radius: 50%;
            border: none;
            color: white;
            cursor: pointer;
        }
        
        /* 侧滑菜单 */
        .side-menu {
            position: fixed;
            top: 0;
            left: 0;
            width: 280px;
            height: 100%;
            background: var(--bg-primary, #fff);
            z-index: 200;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        .side-menu.show {
            transform: translateX(0);
        }
        .menu-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 199;
            display: none;
        }
        .menu-overlay.show {
            display: block;
        }
        
        .menu-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 24px 20px;
            color: white;
        }
        .menu-avatar {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 12px;
            border: 2px solid rgba(255,255,255,0.3);
        }
        .menu-username {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 4px;
        }
        .menu-role {
            font-size: 13px;
            opacity: 0.9;
        }
        
        .menu-list {
            padding: 8px 0;
        }
        .menu-item {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 14px 20px;
            color: var(--text-primary, #333);
            text-decoration: none;
            font-size: 16px;
            border-bottom: 1px solid var(--border-color, #eee);
            transition: background 0.2s;
        }
        .menu-item:hover {
            background: var(--bg-secondary, #f5f5f5);
        }
        .menu-item.active {
            background: rgba(102, 126, 234, 0.1);
            color: #667eea;
        }
        .menu-item .icon {
            width: 24px;
            height: 24px;
        }
        .menu-divider {
            height: 8px;
            background: var(--bg-secondary, #f5f5f5);
            border-top: 1px solid var(--border-color, #eee);
            border-bottom: 1px solid var(--border-color, #eee);
        }
        
        /* 内容区域 */
        .content {
            padding: 16px;
        }
        
        /* 底部导航 */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--bg-primary, #fff);
            display: flex;
            align-items: center;
            justify-content: space-around;
            padding: 8px 0;
            padding-bottom: calc(8px + env(safe-area-inset-bottom, 0));
            box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
            z-index: 99;
            border-top: 1px solid var(--border-color, #eee);
        }
        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
            text-decoration: none;
            color: #999;
            font-size: 12px;
            transition: color 0.2s;
        }
        .nav-item.active {
            color: #667eea;
        }
        .nav-item .icon {
            width: 24px;
            height: 24px;
        }
        
        /* 加载动画 */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.6s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 卡片样式 */
        .card {
            background: var(--bg-primary, #fff);
            border-radius: 16px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            border: 1px solid var(--border-color, #eee);
        }
        
        /* 按钮 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 12px 20px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-primary {
            background: #667eea;
            color: white;
        }
        .btn-primary:hover {
            background: #5a67d8;
        }
        .btn-block {
            width: 100%;
        }

        /* 扫码弹窗 */
        .scan-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.9);
            z-index: 300;
            display: none;
            flex-direction: column;
        }
        .scan-header {
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
        }
        .scan-close {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
        }
        .scan-body {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .scan-result {
            margin-top: 20px;
            color: white;
            text-align: center;
            min-height: 40px;
        }
        .scan-actions {
            padding: 30px 20px;
            display: flex;
            gap: 12px;
        }
        .scan-btn-large {
            flex: 1;
            padding: 16px;
            border-radius: 30px;
            border: none;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
        }
        .scan-btn-primary {
            background: #667eea;
            color: white;
        }
        .scan-btn-secondary {
            background: rgba(255,255,255,0.2);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 顶部导航 -->
    <div class="mobile-header">
        <button class="menu-btn" onclick="toggleMenu()">
            <img src="https://api.iconify.design/mdi:menu.svg?color=white" width="24" height="24" alt="">
        </button>
        <span class="header-title"><?php echo $page_title; ?></span>
        <button class="scan-btn" onclick="openScanner()">
            <img src="https://api.iconify.design/mdi:qrcode-scan.svg?color=white" width="24" height="24" alt="">
        </button>
    </div>
    
    <!-- 侧滑菜单遮罩 -->
    <div class="menu-overlay" id="menuOverlay" onclick="toggleMenu()"></div>
    
    <!-- 侧滑菜单 -->
    <div class="side-menu" id="sideMenu">
        <div class="menu-header">
            <div class="menu-avatar">
                <?php echo mb_substr($user['username'] ?? 'U', 0, 1); ?>
            </div>
            <div class="menu-username"><?php echo htmlspecialchars($user['username']); ?></div>
            <div class="menu-role">
                <?php echo $isAdmin ? '管理员' : '普通用户'; ?>
                · 余额 ¥<?php echo number_format($user['balance'] ?? 0, 2); ?>
            </div>
        </div>
        
        <div class="menu-list">
            <?php foreach ($allowed_pages as $key => $info): ?>
                <a href="?page=<?php echo $key; ?>" class="menu-item <?php echo $page == $key ? 'active' : ''; ?>">
                    <span class="icon">
                        <img src="https://api.iconify.design/mdi:<?php echo $info['icon']; ?>.svg?color=<?php echo $page == $key ? '%23667eea' : '%23666'; ?>" width="24" height="24" alt="">
                    </span>
                    <span><?php echo $info['name']; ?></span>
                </a>
            <?php endforeach; ?>
        </div>
        
        <div class="menu-divider"></div>
        
        <div class="menu-list">
            <a href="index.php" class="menu-item">
                <span class="icon">
                    <img src="https://api.iconify.design/mdi:home.svg?color=%23666" width="24" height="24" alt="">
                </span>
                <span>返回首页</span>
            </a>
            <a href="logout.php" class="menu-item" style="color: #ef4444;">
                <span class="icon">
                    <img src="https://api.iconify.design/mdi:logout.svg?color=%23ef4444" width="24" height="24" alt="">
                </span>
                <span>退出登录</span>
            </a>
        </div>
    </div>
    
    <!-- 内容区域 -->
    <div class="content">
        <?php include $page_file; ?>
    </div>
    
    <!-- 底部导航 -->
    <?php if (count($bottom_nav) > 1): ?>
    <div class="bottom-nav">
        <?php foreach ($bottom_nav as $key => $info): ?>
            <a href="?page=<?php echo $key; ?>" class="nav-item <?php echo $page == $key ? 'active' : ''; ?>">
                <span class="icon">
                    <img src="https://api.iconify.design/mdi:<?php echo $info['icon']; ?>.svg?color=<?php echo $page == $key ? '%23667eea' : '%23999'; ?>" width="24" height="24" alt="">
                </span>
                <span><?php echo $info['name']; ?></span>
            </a>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- 扫码弹窗 -->
    <div class="scan-modal" id="scanModal">
        <div class="scan-header">
            <span>扫一扫</span>
            <button class="scan-close" onclick="closeScanner()">
                <img src="https://api.iconify.design/mdi:close.svg?color=white" width="24" height="24" alt="">
            </button>
        </div>
        <div class="scan-body">
            <div style="position: relative; width: 100%; max-width: 100%; margin: 0 auto;">
                <video id="qr-video" style="width: 100%;  display: block; background: #000;"></video>
                <canvas id="qr-canvas" style="display: none;"></canvas>
                <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; border: 2px solid #667eea;  pointer-events: none;"></div>
            </div>
            <div id="scanResult" class="scan-result"></div>
        </div>
       
    </div>

    <script>
        function toggleMenu() {
            document.getElementById('sideMenu').classList.toggle('show');
            document.getElementById('menuOverlay').classList.toggle('show');
        }
        
        // 点击菜单项后自动关闭
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', function() {
                document.getElementById('sideMenu').classList.remove('show');
                document.getElementById('menuOverlay').classList.remove('show');
            });
        });
        
        // Toast 提示
        window.showToast = function(message, type = 'success') {
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 80px;
                left: 50%;
                transform: translateX(-50%);
                background: ${type === 'success' ? '#10b981' : '#ef4444'};
                color: white;
                padding: 12px 24px;
                border-radius: 40px;
                font-size: 14px;
                z-index: 9999;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                animation: fadeInOut 2s ease;
            `;
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2000);
        };
        
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeInOut {
                0%, 100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
                10%, 90% { opacity: 1; transform: translateX(-50%) translateY(0); }
            }
        `;
        document.head.appendChild(style);

        // ========== 扫码器 ==========
        let videoStream = null;
        let scanning = false;
        let scanInterval = null;
        let currentScannedUrl = '';

        async function openScanner() {
            const modal = document.getElementById('scanModal');
            const video = document.getElementById('qr-video');
            const scanResult = document.getElementById('scanResult');
            
            modal.style.display = 'flex';
            scanResult.innerHTML = '<span style="color: white;">正在启动摄像头...</span>';
            currentScannedUrl = '';
            
            try {
                videoStream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: 'environment' }
                });
                
                video.srcObject = videoStream;
                await video.play();
                
                scanResult.innerHTML = '<span style="color: white;">请将二维码对准扫描框</span>';
                
                scanning = true;
                startScanning();
                
            } catch (error) {
                console.error('摄像头错误:', error);
                let errorMsg = '无法访问摄像头';
                if (error.name === 'NotAllowedError') {
                    errorMsg = '请允许访问摄像头';
                } else if (error.name === 'NotFoundError') {
                    errorMsg = '未找到摄像头';
                }
                scanResult.innerHTML = '<span style="color: #ef4444;">' + errorMsg + '</span>';
            }
        }

        function startScanning() {
            const video = document.getElementById('qr-video');
            const canvas = document.getElementById('qr-canvas');
            const ctx = canvas.getContext('2d', { willReadFrequently: true });
            
            scanInterval = setInterval(() => {
                if (!scanning) return;
                
                if (video.readyState === video.HAVE_ENOUGH_DATA) {
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    
                    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    
                    if (typeof jsQR !== 'undefined') {
                        const code = jsQR(imageData.data, canvas.width, canvas.height, {
                            inversionAttempts: 'dontInvert'
                        });
                        
                        if (code && code.data) {
                            handleScanSuccess(code.data);
                        }
                    }
                }
            }, 150);
        }

        function handleScanSuccess(url) {
    if (!scanning) return;
    
    currentScannedUrl = url;
    scanning = false;
    stopScanning();
    
    // 如果是登录二维码，跳转到确认页面
    if (currentScannedUrl.includes('/qrcode_scan.php')) {
        // 直接跳转到确认页面
        window.location.href = currentScannedUrl;
    } else {
        // 普通链接，直接跳转
        window.location.href = currentScannedUrl;
    }
}

        function stopScanning() {
            if (scanInterval) {
                clearInterval(scanInterval);
                scanInterval = null;
            }
        }

        function closeScanner() {
            stopScanning();
            scanning = false;
            
            if (videoStream) {
                videoStream.getTracks().forEach(track => track.stop());
                videoStream = null;
            }
            
            const video = document.getElementById('qr-video');
            if (video) video.srcObject = null;
            
            document.getElementById('scanModal').style.display = 'none';
            document.getElementById('scanResult').innerHTML = '';
            currentScannedUrl = '';
        }

        function getTokenFromUrl(url) {
            const match = url.match(/token=([^&]+)/);
            return match ? match[1] : '';
        }

        function confirmScan() {
            if (currentScannedUrl) {
                if (currentScannedUrl.includes('/qrcode_scan.php')) {
                    const token = getTokenFromUrl(currentScannedUrl);
                    fetch('/api/qrcode_confirm.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: 'token=' + token + '&action=confirm'
                    }).then(res => res.json()).then(data => {
                        if (data.code === 0) {
                            showToast('登录成功！');
                            closeScanner();
                            setTimeout(() => location.href = '/m/', 1000);
                        } else {
                            showToast(data.msg || '确认失败');
                        }
                    });
                } else {
                    // 普通链接，直接跳转
                    window.location.href = currentScannedUrl;
                }
            } else {
                showToast('请先扫描二维码');
            }
        }
        // 检测 PC 端登录请求
function checkPcLoginRequest() {
    fetch('/api/pc_login_pending.php')
        .then(res => res.json())
        .then(data => {
            if (data.has_pending) {
                // 有待确认请求，跳转到确认页面
                window.location.href = '/m/pc_login_confirm.php?token=' + data.token;
            }
        });
}

// 每 3 秒检测一次
setInterval(checkPcLoginRequest, 1000);
    </script>
</body>
</html>