<?php
if (!defined('IN_CRONLITE')) {
    require_once __DIR__ . '/../../../MPHX/common.php';
}

if (!isset($user) || !$user) {
    $user = check_user();
}
if (!isset($bt) || !$bt) {
    $bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>用户控制面板 - MLEOE宝塔系统</title>
    
    <!-- DNS预解析 -->
    <link rel="dns-prefetch" href="//cdn.jsdelivr.net">
    <link rel="preconnect" href="//cdn.jsdelivr.net" crossorigin>
    
    <!-- 关键CSS内联加载 -->
    <style>
        /* 首屏关键样式 - 防止FOUC */
        html,body{margin:0;padding:0;height:100%;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
        .sidebar{position:fixed;left:0;top:0;width:220px;height:100%;background:#1a1d29;color:#fff;z-index:1000;overflow-y:auto}
        .main-content{margin-left:220px;min-height:100vh;background:#f5f5f5}
        .loading-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.9);z-index:9999;display:flex;align-items:center;justify-content:center;flex-direction:column}
        .loading-spinner{width:40px;height:40px;border:3px solid #f3f3f3;border-top:3px solid #188038;border-radius:50%;animation:spin 1s linear infinite}
        @keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}
    </style>
    
    <!-- 异步加载非关键CSS -->
    <link rel="preload" href="/static/css/bootstrap.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link rel="stylesheet" href="/static/css/bootstrap.min.css"></noscript>
    
    <link rel="preload" href="/static/css/all.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link rel="stylesheet" href="/static/css/all.min.css"></noscript>
    
    <link rel="stylesheet" href="/templates/default/assets/css/style.css?v=20260406_1">
    
    <!-- 预加载关键JS -->
    <link rel="preload" href="/static/js/jquery.min.js" as="script">
</head>
<body>
    <div class="sidebar">
        <div class="brand" data-title="<?php echo $conf['name']; ?>">
            <i class="fas fa-laptop"></i> <span><?php echo $conf['name']; ?></span>
        </div>
        <div class="menu">
            <div class="menu-item active menu-link" data-url="sy.php" data-title="<?php echo L('dashboard', 'menu'); ?>">
                <i class="fas fa-home"></i> <span><?php echo L('dashboard', 'menu'); ?></span>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="website" data-title="<?php echo L('website_config', 'menu'); ?>">
                <i class="fas fa-globe"></i> <span><?php echo L('website_config', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="website">
                <div class="submenu-item submenu-link" data-url="set.php?gn=php" data-title="<?php echo L('php_version', 'menu'); ?>"><?php echo L('php_version', 'menu'); ?></div>
                <div class="submenu-item submenu-link" data-url="set.php?gn=ym" data-title="<?php echo L('domain_modify', 'menu'); ?>"><?php echo L('domain_modify', 'menu'); ?></div>
                <div class="submenu-item submenu-link" data-url="set.php?gn=mrwd" data-title="<?php echo L('default_doc', 'menu'); ?>"><?php echo L('default_doc', 'menu'); ?></div>
                <div class="submenu-item submenu-link" data-url="set.php?gn=yxml" data-title="<?php echo L('run_dir', 'menu'); ?>"><?php echo L('run_dir', 'menu'); ?></div>
                <div class="submenu-item submenu-link" data-url="set.php?gn=wjt" data-title="<?php echo L('rewrite', 'menu'); ?>"><?php echo L('rewrite', 'menu'); ?></div>
                <div class="submenu-item submenu-link" data-url="set.php?gn=zml" data-title="<?php echo L('subdirectory_binding', 'menu'); ?>"><?php echo L('subdirectory_binding', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="security" data-title="<?php echo L('security_management', 'menu'); ?>">
                <i class="fas fa-shield-alt"></i> <span><?php echo L('security_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="security">
                <div class="submenu-item" data-action="load-page" data-page="set.php?gn=ssl" data-title="<?php echo L('ssl', 'menu'); ?>"><?php echo L('ssl', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="set.php?gn=fdl" data-title="<?php echo L('anti_hotlink', 'menu'); ?>"><?php echo L('anti_hotlink', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="set.php?gn=pass" data-title="<?php echo L('set_password', 'menu'); ?>"><?php echo L('set_password', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="set.php?gn=pass" data-title="<?php echo L('access_restriction', 'menu'); ?>"><?php echo L('access_restriction', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="file" data-title="<?php echo L('file_management', 'menu'); ?>">
                <i class="fas fa-folder"></i> <span><?php echo L('file_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="file">
                <div class="submenu-item" data-action="load-page" data-page="file.php" data-title="<?php echo L('file_manager', 'menu'); ?>"><?php echo L('file_manager', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="ftp_settings.php" data-title="<?php echo L('ftp_settings', 'menu'); ?>"><?php echo L('ftp_settings', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="database" data-title="<?php echo L('database_management', 'menu'); ?>">
                <i class="fas fa-database"></i> <span><?php echo L('database_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="database">
                <div class="submenu-item" data-action="load-page" data-page="sql.php" data-title="<?php echo L('sql_manager', 'menu'); ?>"><?php echo L('sql_manager', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="sqlqx.php" data-title="<?php echo L('sql_permission', 'menu'); ?>"><?php echo L('sql_permission', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="backup" data-title="<?php echo L('backup_management', 'menu'); ?>">
                <i class="fas fa-archive"></i> <span><?php echo L('backup_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="backup">
                <div class="submenu-item" data-action="load-page" data-page="backup.php" data-title="<?php echo L('backup_restore', 'menu'); ?>"><?php echo L('backup_restore', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="monitor" data-title="<?php echo L('system_monitor', 'menu'); ?>">
                <i class="fas fa-chart-line"></i> <span><?php echo L('system_monitor', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="monitor">
                <div class="submenu-item" data-action="load-page" data-page="traffic.php" data-title="<?php echo L('traffic_stats', 'menu'); ?>"><?php echo L('traffic_stats', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="cron.php" data-title="<?php echo L('cron_job', 'menu'); ?>"><?php echo L('cron_job', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="finance" data-title="<?php echo L('finance_management', 'menu'); ?>">
                <i class="fas fa-credit-card"></i> <span><?php echo L('finance_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="finance">
                <div class="submenu-item" data-action="load-page" data-page="pay.php" data-title="<?php echo L('recharge_center', 'menu'); ?>"><?php echo L('recharge_center', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="orders.php" data-title="<?php echo L('order_history', 'menu'); ?>"><?php echo L('order_history', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="deploy" data-title="<?php echo L('one_click_deploy', 'menu'); ?>">
                <i class="fas fa-rocket"></i> <span><?php echo L('one_click_deploy', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="deploy">
                <div class="submenu-item" data-action="load-page" data-page="deploy.php" data-title="<?php echo L('deploy_program', 'menu'); ?>"><?php echo L('deploy_program', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="deploy_logs.php" data-title="<?php echo L('deploy_history', 'menu'); ?>"><?php echo L('deploy_history', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="app" data-title="<?php echo L('app_management', 'menu'); ?>">
                <i class="fas fa-mobile-alt"></i> <span><?php echo L('app_management', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="app">
                <div class="submenu-item" data-action="load-page" data-page="app_access.php" data-title="<?php echo L('app_access', 'menu'); ?>"><?php echo L('app_access', 'menu'); ?></div>
            </div>
            <div class="menu-item menu-toggle" data-toggle-id="personal" data-title="<?php echo L('personal_center', 'menu'); ?>">
                <i class="fas fa-user"></i> <span><?php echo L('personal_center', 'menu'); ?></span> <i class="fas fa-chevron-down arrow"></i>
            </div>
            <div class="submenu" id="personal">
                <div class="submenu-item" data-action="load-page" data-page="profile.php" data-title="<?php echo L('profile', 'menu'); ?>"><?php echo L('profile', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="logs.php" data-title="<?php echo L('logs', 'menu'); ?>"><?php echo L('logs', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="notifications.php" data-title="<?php echo L('notifications', 'menu'); ?>"><?php echo L('notifications', 'menu'); ?></div>
                <div class="submenu-item" data-action="load-page" data-page="notification-settings.php" data-title="<?php echo L('notification_settings', 'menu'); ?>"><?php echo L('notification_settings', 'menu'); ?></div>
            </div>
        </div>
    </div>
    
    <!-- 页面加载动画 -->
    <div id="pageLoader" class="loading-overlay" style="display: none; opacity: 0; transition: opacity 0.3s;">
        <div class="loading-spinner"></div>
        <p style="margin-top: 15px; color: #666;">加载中...</p>
    </div>
    
    <div class="main-content">
        <div class="header">
            <!-- 侧边栏伸缩按钮 (移动到 Header 内) -->
            <div class="sidebar-toggle" id="sidebarToggle" title="点击展开/收缩侧边栏">
                <i class="fas fa-bars"></i>
            </div>
            <h4><?php echo L('dashboard', 'menu'); ?></h4>
            <div class="user-info">
                <span><i class="fas fa-user-circle"></i> <?php echo L('user', 'menu'); ?>: <?php echo $user['user']; ?></span>
                <select class="form-control" id="langSelect" style="width: auto; display: inline-block; margin: 0 10px;" onchange="changeLanguage(this.value)">
                    <option value="zh_CN" <?php echo $lang_code == 'zh_CN' ? 'selected' : ''; ?>>中文</option>
                    <option value="en_US" <?php echo $lang_code == 'en_US' ? 'selected' : ''; ?>>English</option>
                </select>
                <a href="ajax.php?egn=login&logout=1" class="btn btn-danger btn-sm">
                    <i class="fas fa-sign-out-alt"></i> <?php echo L('logout', 'menu'); ?>
                </a>
            </div>
        </div>
        <div class="content-area">
            <div class="card" style="padding: 0; overflow: visible; min-height: 800px;">
                <iframe id="mainFrame" src="sy.php" style="width: 100%; min-height: 800px; border: none; height: auto;"></iframe>
            </div>
        </div>
    </div>
    
    <!-- 同步加载jQuery（页面功能依赖它） -->
    <script src="/static/js/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/layer/3.5.1/layer.js"></script>
    <script src="/templates/default/assets/js/page-loader.js"></script>
    <script>
    // 侧边栏伸缩功能 - 响应式适配
    $(document).ready(function() {
        var toggleBtn = document.getElementById('sidebarToggle');
        var sidebar = document.querySelector('.sidebar');
        var mainContent = document.querySelector('.main-content');
        
        // 创建遮罩层
        var overlay = document.createElement('div');
        overlay.className = 'sidebar-overlay';
        overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:999;display:none;opacity:0;transition:opacity 0.3s;';
        document.body.appendChild(overlay);

        function toggleSidebar() {
            var isMobile = window.innerWidth <= 768;
            
            if (isMobile) {
                // 移动端：切换 active 类和遮罩层
                var isActive = sidebar.classList.toggle('active');
                if (isActive) {
                    overlay.style.display = 'block';
                    setTimeout(function() { overlay.style.opacity = 1; }, 10);
                } else {
                    overlay.style.opacity = 0;
                    setTimeout(function() { overlay.style.display = 'none'; }, 300);
                }
            } else {
                // PC端：切换 sidebar-collapsed 类
                document.body.classList.toggle('sidebar-collapsed');
                // 保存状态
                var isCollapsed = document.body.classList.contains('sidebar-collapsed');
                localStorage.setItem('sidebarCollapsed', isCollapsed);
                
                // 更新按钮图标
                var icon = toggleBtn.querySelector('i');
                if (icon) {
                    icon.className = isCollapsed ? 'fas fa-chevron-right' : 'fas fa-bars';
                }
            }
        }

        if (toggleBtn) {
            toggleBtn.addEventListener('click', toggleSidebar);
        }
        
        // 点击遮罩层关闭侧边栏
        overlay.addEventListener('click', function() {
            sidebar.classList.remove('active');
            overlay.style.opacity = 0;
            setTimeout(function() { overlay.style.display = 'none'; }, 300);
        });
        
        // 恢复保存的状态 (仅PC端)
        if (window.innerWidth > 768) {
            var savedState = localStorage.getItem('sidebarCollapsed');
            if (savedState === 'true') {
                document.body.classList.add('sidebar-collapsed');
                var savedIcon = toggleBtn.querySelector('i');
                if (savedIcon) {
                    savedIcon.className = 'fas fa-chevron-right';
                }
            }
        }
        
        // 初始化菜单点击事件
        var menuItems = document.querySelectorAll('.menu-item');
        menuItems.forEach(function(item) {
            item.addEventListener('click', function() {
                var onclick = this.getAttribute('onclick') || '';
                if (onclick.indexOf('toggleSubmenu') === -1) {
                    document.querySelectorAll('.menu-item').forEach(function(mi) {
                        mi.classList.remove('active');
                    });
                    this.classList.add('active');
                }
            });
        });
    });
    
    function changeLanguage(lang) {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                egn: 'changelanguage',
                lang: lang
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 'success') {
                    location.reload();
                } else {
                    alert(data.code);
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', status, error);
                console.log('Response:', xhr.responseText);
                alert('语言切换失败，请重试');
            }
        });
    }
    
    function loadPage(url) {
        // 添加版本参数，避免缓存问题
        var timestamp = new Date().getTime();
        var urlWithTimestamp = url + (url.indexOf('?') === -1 ? '?' : '&') + 'v=' + timestamp;
        $('#mainFrame').attr('src', urlWithTimestamp);
    }
    
    $(document).ready(function() {
        // 菜单点击事件已在上方初始化
        
        // 检查是否需要邮箱验证
        checkEmailVerify();
    });
    
    // 检查邮箱验证
    function checkEmailVerify() {
        // 从sessionStorage检查登录时标记的需要验证
        if (sessionStorage.getItem('need_email_verify') === 'true') {
            sessionStorage.removeItem('need_email_verify');
            showEmailVerifyDialog();
        }
    }
    
    // 显示邮箱验证弹窗
    function showEmailVerifyDialog() {
        var html = '<div style="padding:20px;">';
        html += '<div class="alert alert-info" style="margin-bottom:15px;"><i class="fas fa-info-circle"></i> 系统要求绑定邮箱，请输入您的邮箱地址并验证</div>';
        html += '<div class="form-group" style="margin-bottom:15px;">';
        html += '<label>邮箱地址</label>';
        html += '<div style="display:flex;gap:10px;">';
        html += '<input type="email" id="verifyEmail" class="form-control" placeholder="请输入邮箱地址" style="flex:1;">';
        html += '<button type="button" class="btn btn-secondary" onclick="sendVerifyCode()" id="sendCodeBtn">获取验证码</button>';
        html += '</div>';
        html += '</div>';
        html += '<div class="form-group">';
        html += '<label>验证码</label>';
        html += '<input type="text" id="verifyCode" class="form-control" placeholder="请输入6位验证码">';
        html += '</div>';
        html += '</div>';
        
        layer.open({
            type: 1,
            title: '邮箱验证',
            area: ['450px', 'auto'],
            closeBtn: 0,
            shadeClose: false,
            btn: ['验证', '退出登录'],
            content: html,
            yes: function(index) {
                verifyEmail(index);
            },
            btn2: function() {
                // 退出登录
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: {egn: 'login', logout: 1},
                    dataType: 'json',
                    success: function() {
                        location.href = 'login.php';
                    }
                });
            }
        });
    }
    
    // 发送验证码
    function sendVerifyCode() {
        var email = $('#verifyEmail').val();
        if (!email) {
            layer.msg('请输入邮箱地址');
            return;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            layer.msg('邮箱格式不正确');
            return;
        }
        
        var $btn = $('#sendCodeBtn');
        $btn.prop('disabled', true).text('发送中...');
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                egn: 'send_email_verify_code',
                email: email
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 'success') {
                    layer.msg('验证码已发送');
                    // 倒计时
                    var count = 60;
                    var timer = setInterval(function() {
                        $btn.text(count + '秒后重试');
                        count--;
                        if (count < 0) {
                            clearInterval(timer);
                            $btn.prop('disabled', false).text('获取验证码');
                        }
                    }, 1000);
                } else {
                    layer.msg(data.msg || '发送失败');
                    $btn.prop('disabled', false).text('获取验证码');
                }
            },
            error: function() {
                layer.msg('网络错误');
                $btn.prop('disabled', false).text('获取验证码');
            }
        });
    }
    
    // 验证邮箱
    function verifyEmail(layerIndex) {
        var email = $('#verifyEmail').val();
        var code = $('#verifyCode').val();
        
        if (!email || !code) {
            layer.msg('请输入邮箱和验证码');
            return;
        }
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                egn: 'verify_email',
                email: email,
                code: code
            },
            dataType: 'json',
            success: function(data) {
                if (data.code === 'success') {
                    layer.msg('邮箱验证成功', {icon: 1});
                    layer.close(layerIndex);
                } else {
                    layer.msg(data.msg || '验证失败');
                }
            },
            error: function() {
                layer.msg('网络错误');
            }
        });
    }
    
    // 事件委托：侧边菜单点击
    $(document).on('click', '.menu-link', function() {
        var url = $(this).data('url');
        if (url) loadPage(url);
    });

    $(document).on('click', '.submenu-link', function(e) {
        var url = $(this).data('url');
        if (url) loadPage(url);
    });

    // 事件代理：侧边菜单加载页面
    $(document).on('click', '.submenu-item[data-action="load-page"]', function(e){
        var page = $(this).attr('data-page');
        if (page) loadPage(page);
    });

    // 切换子菜单（替代 inline toggleSubmenu）
    $(document).on('click', '.menu-toggle', function(e) {
        // 阻止冒泡，避免触发 document 上的其他点击事件
        e.stopPropagation();
        var toggleId = $(this).data('toggle-id');
        if (!toggleId) return;
        
        var $submenu = $('#' + toggleId);
        var $arrow = $(this).find('.arrow');
        
        // 切换当前子菜单
        $submenu.slideToggle(200);
        $(this).toggleClass('expanded');
        
        // 旋转箭头
        if ($(this).hasClass('expanded')) {
            $arrow.css('transform', 'rotate(180deg)');
        } else {
            $arrow.css('transform', 'rotate(0deg)');
        }
    });
    </script>
</body>
</html>
