<?php
/**
 * 一课 管理后台主框架
 * 参考SaiAdmin布局：左侧侧边栏 + 顶部工具栏 + 内容区
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/AdminAuth.php';

$auth = new AdminAuth();
$auth->requireLogin();

$db = getDB();
$page = isset($_GET['page']) ? trim($_GET['page']) : 'dashboard';

// 允许的页面列表
$allowedPages = ['dashboard', 'categories', 'functions', 'popups', 'site', 'system', 'users', 'sections'];
if (!in_array($page, $allowedPages)) {
    $page = 'dashboard';
}

// 获取统计数据
$categoryCount = $db->query("SELECT COUNT(*) as cnt FROM function_categories")->fetch()['cnt'];
$functionCount = $db->query("SELECT COUNT(*) as cnt FROM functions")->fetch()['cnt'];
$userCount = $db->query("SELECT COUNT(*) as cnt FROM users")->fetch()['cnt'];
$popupCount = $db->query("SELECT COUNT(*) as cnt FROM popups")->fetch()['cnt'];

// 获取站点配置
$siteConfig = [];
$stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'site'");
foreach ($stmt->fetchAll() as $row) {
    $siteConfig[$row['key_name']] = $row['value'];
}
$siteTitle = $siteConfig['site_title'] ?? SITE_NAME;

// 页面名称映射
$pageNames = [
    'dashboard' => '仪表盘',
    'categories' => '分类管理',
    'functions' => '菜单管理',
    'popups' => '弹窗管理',
    'site' => '站点配置',
    'system' => '系统配置',
    'users' => '用户管理',
    'sections' => '课节管理',
];
$pageTitle = $pageNames[$page] ?? '仪表盘';

// 管理员信息
$adminNickname = $_SESSION['admin_nickname'] ?? $_SESSION['admin_username'] ?? 'admin';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - <?php echo htmlspecialchars($siteTitle); ?>管理后台</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/css/admin.css?v=1">
</head>
<body>

<div class="admin-layout">
    <!-- 左侧导航 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-shield-alt"></i>
            <div class="brand"><?php echo htmlspecialchars($siteTitle); ?></div>
        </div>

        <div class="sidebar-nav">
            <div class="nav-group-title">核心功能</div>
            <div class="nav-item <?php echo $page === 'dashboard' ? 'active' : ''; ?>" onclick="navTo('dashboard')">
                <i class="fas fa-tachometer-alt"></i>
                <span class="nav-text">仪表盘</span>
            </div>
            <div class="nav-item <?php echo $page === 'categories' ? 'active' : ''; ?>" onclick="navTo('categories')">
                <i class="fas fa-layer-group"></i>
                <span class="nav-text">分类管理</span>
            </div>
            <div class="nav-item <?php echo $page === 'functions' ? 'active' : ''; ?>" onclick="navTo('functions')">
                <i class="fas fa-th-large"></i>
                <span class="nav-text">菜单管理</span>
            </div>
            <div class="nav-item <?php echo $page === 'popups' ? 'active' : ''; ?>" onclick="navTo('popups')">
                <i class="fas fa-comment-dots"></i>
                <span class="nav-text">弹窗公告</span>
            </div>

            <div class="nav-group-title">系统设置</div>
            <div class="nav-item <?php echo $page === 'site' ? 'active' : ''; ?>" onclick="navTo('site')">
                <i class="fas fa-globe"></i>
                <span class="nav-text">站点配置</span>
            </div>
            <div class="nav-item <?php echo $page === 'system' ? 'active' : ''; ?>" onclick="navTo('system')">
                <i class="fas fa-cogs"></i>
                <span class="nav-text">系统配置</span>
            </div>

            <div class="nav-group-title">数据管理</div>
            <div class="nav-item <?php echo $page === 'sections' ? 'active' : ''; ?>" onclick="navTo('sections')">
                <i class="fas fa-clock"></i>
                <span class="nav-text">课节管理</span>
            </div>
            <div class="nav-item <?php echo $page === 'users' ? 'active' : ''; ?>" onclick="navTo('users')">
                <i class="fas fa-users"></i>
                <span class="nav-text">用户管理</span>
            </div>

            <div class="nav-group-title">账号安全</div>
            <div class="nav-item" onclick="showChangePasswordModal()">
                <i class="fas fa-key"></i>
                <span class="nav-text">修改密码</span>
            </div>
        </div>

        <div class="sidebar-footer">
            <div class="toggle-btn" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </div>
        </div>
    </div>

    <!-- 右侧主区域 -->
    <div class="main-area">
        <!-- 顶部栏 -->
        <div class="top-bar">
            <div class="top-bar-left">
                <div class="breadcrumb">
                    <span><?php echo htmlspecialchars($pageTitle); ?></span>
                </div>
            </div>
            <div class="top-bar-right">
                <div class="admin-info">
                    <div class="avatar"><i class="fas fa-user"></i></div>
                    <span><?php echo htmlspecialchars($adminNickname); ?></span>
                </div>
                <button class="pwd-btn" onclick="showChangePasswordModal()" title="修改密码"><i class="fas fa-key"></i></button>
                <button class="logout-btn" onclick="doLogout()"><i class="fas fa-sign-out-alt"></i> 退出</button>
            </div>
        </div>

        <!-- 内容区 -->
        <div class="content-area" id="contentArea">
            <?php
            // 根据page参数加载不同模块
            switch ($page) {
                case 'dashboard':
                    include __DIR__ . '/modules/dashboard.php';
                    break;
                case 'categories':
                    include __DIR__ . '/modules/categories.php';
                    break;
                case 'functions':
                    include __DIR__ . '/modules/functions.php';
                    break;
                case 'popups':
                    include __DIR__ . '/modules/popups.php';
                    break;
                case 'site':
                    include __DIR__ . '/modules/site.php';
                    break;
                case 'system':
                    include __DIR__ . '/modules/system.php';
                    break;
                case 'users':
                    include __DIR__ . '/modules/users.php';
                    break;
                case 'sections':
                    include __DIR__ . '/modules/sections.php';
                    break;
            }
            ?>
        </div>
    </div>
</div>

<!-- Toast容器 -->
<div class="toast-container" id="toastContainer"></div>

<!-- 模态框容器 -->
<div id="modalContainer"></div>

<script>
// 导航跳转
function navTo(page) {
    location.href = '?page=' + page;
}

// 切换侧边栏
function toggleSidebar() {
    var sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('collapsed');
}

// 退出登录
function doLogout() {
    fetch('<?php echo SITE_URL; ?>/admin/api.php?action=logout')
        .then(function() { location.href = 'login.php'; });
}

// Toast提示
function showToast(msg, type) {
    type = type || 'info';
    var container = document.getElementById('toastContainer');
    var toast = document.createElement('div');
    toast.className = 'toast-item ' + type;
    toast.innerHTML = '<i class="fas ' + (type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-times-circle' : 'fa-info-circle') + '"></i>' + msg;
    container.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 3000);
}

// API请求封装
function apiRequest(action, data, callback) {
    data = data || {};
    data.action = action;

    var formData = new FormData();
    for (var key in data) {
        formData.append(key, data[key]);
    }

    fetch('<?php echo SITE_URL; ?>/admin/api.php', {
        method: 'POST',
        body: formData
    })
    .then(function(res) {
        return res.text().then(function(text) {
            try { return JSON.parse(text); }
            catch(e) { throw new Error('服务器响应异常'); }
        });
    })
    .then(function(result) {
        if (callback) callback(result);
    })
    .catch(function(err) {
        showToast(err.message || '请求失败', 'error');
    });
}

// 显示模态框
function showModal(title, bodyHtml, footerHtml) {
    var container = document.getElementById('modalContainer');
    container.innerHTML = '<div class="modal-overlay" onclick="if(event.target===this)closeModal()">' +
        '<div class="modal-box">' +
        '<div class="modal-header"><h3>' + title + '</h3><div class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></div></div>' +
        '<div class="modal-body">' + bodyHtml + '</div>' +
        (footerHtml ? '<div class="modal-footer">' + footerHtml + '</div>' : '') +
        '</div></div>';
}

function closeModal() {
    document.getElementById('modalContainer').innerHTML = '';
}

// 确认对话框
function confirmAction(msg, onConfirm) {
    showModal('确认操作', '<p style="font-size:14px;color:#374151;">' + msg + '</p>',
        '<button class="btn-secondary" onclick="closeModal()">取消</button>' +
        '<button class="btn-primary" onclick="closeModal();' + onConfirm + '()">确定</button>');
}

function showChangePasswordModal() {
    var body = '<div style="padding:4px 0;">' +
        '<div class="form-group">' +
        '<label class="form-label">旧密码</label>' +
        '<input type="password" id="pwd_old" class="form-input" placeholder="请输入当前密码">' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">新密码</label>' +
        '<input type="password" id="pwd_new" class="form-input" placeholder="至少6位">' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">确认新密码</label>' +
        '<input type="password" id="pwd_confirm" class="form-input" placeholder="再次输入新密码">' +
        '</div>' +
        '</div>';
    var footer = '<button class="btn-secondary" onclick="closeModal()">取消</button>' +
        '<button class="btn-primary" onclick="doChangePassword()">确认修改</button>';
    showModal('修改密码', body, footer);
}

function doChangePassword() {
    var oldPwd = document.getElementById('pwd_old').value;
    var newPwd = document.getElementById('pwd_new').value;
    var confirmPwd = document.getElementById('pwd_confirm').value;

    if (!oldPwd || !newPwd) {
        showToast('旧密码和新密码不能为空', 'error');
        return;
    }
    if (newPwd !== confirmPwd) {
        showToast('新密码与确认密码不一致', 'error');
        return;
    }
    if (newPwd.length < 6) {
        showToast('新密码长度不能少于6位', 'error');
        return;
    }

    apiRequest('change_password', {
        old_password: oldPwd,
        new_password: newPwd,
        confirm_password: confirmPwd
    }, function(data) {
        if (data.code === 1) {
            showToast('密码修改成功', 'success');
            closeModal();
        } else {
            showToast(data.msg || '密码修改失败', 'error');
        }
    });
}
</script>

</body>
</html>