<?php
/**
 * 菜单管理模块 — 页面路径内置下拉选择 + 图标支持上传自定义图标
 */
$db = getDB();
$categories = $db->query("SELECT * FROM function_categories ORDER BY sort_order")->fetchAll();
$functions = $db->query("SELECT f.*, c.name as category_name FROM functions f LEFT JOIN function_categories c ON f.category_id = c.id ORDER BY c.sort_order, f.sort_order")->fetchAll();

// 内置页面路径列表
$builtinPages = [
    ['path' => 'pages/schedule.php', 'label' => '课表'],
    ['path' => 'pages/grades.php', 'label' => '成绩'],
    ['path' => 'pages/exam.php', 'label' => '考试安排'],
    ['path' => 'pages/classroom.php', 'label' => '空教室'],
    ['path' => 'pages/academic.php', 'label' => '学业详情'],
    ['path' => 'pages/gpa.php', 'label' => 'GPA计算'],
    ['path' => 'pages/custom.php', 'label' => '自定义课程'],
    ['path' => 'pages/history.php', 'label' => '历史上的今天'],
    ['path' => 'pages/profile.php', 'label' => '个人中心'],
    ['path' => 'pages/help.php', 'label' => '使用说明'],
    ['path' => 'pages/about.php', 'label' => '关于我们'],
    ['path' => 'pages/map.php', 'label' => '校园地图'],
];

// 内置图标列表
$builtinIcons = [
    'fa-link', 'fa-calendar-alt', 'fa-graduation-cap', 'fa-clipboard-list', 'fa-chalkboard',
    'fa-calculator', 'fa-book-open', 'fa-plus-circle', 'fa-map-marked-alt', 'fa-user',
    'fa-info-circle', 'fa-school', 'fa-heart', 'fa-running', 'fa-camera',
    'fa-search', 'fa-comments', 'fa-users', 'fa-certificate', 'fa-id-card',
    'fa-chalkboard-teacher', 'fa-folder', 'fa-th-large', 'fa-ellipsis-h', 'fa-globe',
    'fa-cogs', 'fa-chart-line', 'fa-heartbeat', 'fa-comment-dots', 'fa-bolt',
    'fa-star', 'fa-fire', 'fa-trophy', 'fa-music', 'fa-gamepad',
    'fa-shopping-cart', 'fa-phone', 'fa-envelope', 'fa-newspaper', 'fa-cloud',
    'fa-history', 'fa-landmark',
];
?>

<div class="toolbar">
    <div class="toolbar-title">菜单管理</div>
    <div class="toolbar-actions">
        <button class="btn-primary" onclick="showFunctionModal()"><i class="fas fa-plus"></i> 新增菜单</button>
    </div>
</div>

<div class="panel-card">
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>所属分类</th>
                <th>名称</th>
                <th>图标</th>
                <th>页面路径</th>
                <th>外链</th>
                <th>排序</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($functions as $func): ?>
            <tr>
                <td><?php echo $func['id']; ?></td>
                <td><?php echo htmlspecialchars($func['category_name']); ?></td>
                <td><?php echo htmlspecialchars($func['name']); ?></td>
                <td>
                    <?php if (strpos($func['icon'], 'http') === 0 || strpos($func['icon'], '/uploads/') === 0): ?>
                    <img src="<?php echo htmlspecialchars($func['icon']); ?>" style="width:24px;height:24px;object-fit:contain;border-radius:4px;">
                    <?php else: ?>
                    <i class="fas <?php echo htmlspecialchars($func['icon']); ?>" style="font-size:16px;"></i>
                    <?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($func['page_url'] ?: '-'); ?></td>
                <td><?php echo $func['is_external'] ? '<span class="status-tag active">外链</span>' : '<span class="status-tag inactive">内页</span>'; ?></td>
                <td><?php echo $func['sort_order']; ?></td>
                <td>
                    <div class="table-actions">
                        <button class="btn-sm btn-edit" onclick="editFunction(<?php echo $func['id']; ?>)">编辑</button>
                        <button class="btn-sm btn-del" onclick="deleteFunction(<?php echo $func['id']; ?>)">删除</button>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($functions)): ?>
            <tr><td colspan="8" style="text-align:center;color:#9ca3af;padding:32px;">暂无菜单数据</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
var categories = <?php echo json_encode($categories, JSON_UNESCAPED_UNICODE); ?>;
var builtinPages = <?php echo json_encode($builtinPages, JSON_UNESCAPED_UNICODE); ?>;
var builtinIcons = <?php echo json_encode($builtinIcons, JSON_UNESCAPED_UNICODE); ?>;

var currentIconType = 'builtin'; // 'builtin' or 'custom'
var currentCustomIconUrl = '';

function showFunctionModal(id, catId, name, icon, pageUrl, extUrl, isExt, sort) {
    id = id || 0;
    catId = catId || '';
    name = name || '';
    icon = icon || 'fa-link';
    pageUrl = pageUrl || '';
    extUrl = extUrl || '';
    isExt = isExt || 0;
    sort = sort || 0;
    var isEdit = id > 0;

    // 判断图标类型
    if (icon && (icon.indexOf('http') === 0 || icon.indexOf('/uploads/') === 0)) {
        currentIconType = 'custom';
        currentCustomIconUrl = icon;
    } else {
        currentIconType = 'builtin';
        currentCustomIconUrl = '';
    }

    var catOptions = '<option value="">请选择分类</option>';
    for (var i = 0; i < categories.length; i++) {
        var selected = categories[i].id == catId ? ' selected' : '';
        catOptions += '<option value="' + categories[i].id + '"' + selected + '>' + categories[i].name + '</option>';
    }

    var pageOptions = '<option value="">请选择页面</option>';
    for (var i = 0; i < builtinPages.length; i++) {
        var selected = builtinPages[i].path == pageUrl ? ' selected' : '';
        pageOptions += '<option value="' + builtinPages[i].path + '"' + selected + '>' + builtinPages[i].label + ' (' + builtinPages[i].path + ')</option>';
    }

    var iconOptions = '';
    for (var i = 0; i < builtinIcons.length; i++) {
        var selected = builtinIcons[i] == icon ? ' selected' : '';
        iconOptions += '<option value="' + builtinIcons[i] + '"' + selected + '>' + builtinIcons[i] + '</option>';
    }

    var iconPreview = currentIconType === 'custom' ?
        '<div style="margin-top:8px;"><img src="' + currentCustomIconUrl + '" style="width:32px;height:32px;object-fit:contain;border-radius:4px;"></div>' :
        '<div style="margin-top:8px;font-size:24px;color:#374151;"><i class="fas ' + (icon || 'fa-link') + '" id="iconPreviewIcon"></i></div>';

    var body = '<div class="form-group">' +
        '<label class="form-label">所属分类</label>' +
        '<select class="form-select" id="func_cat">' + catOptions + '</select>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">菜单名称</label>' +
        '<input class="form-input" id="func_name" value="' + name + '" placeholder="如：查课表">' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">图标类型</label>' +
        '<div style="display:flex;gap:12px;margin-bottom:8px;">' +
        '<label style="display:flex;align-items:center;gap:4px;font-size:14px;cursor:pointer;">' +
        '<input type="radio" name="icon_type" value="builtin" ' + (currentIconType === 'builtin' ? 'checked' : '') + ' onchange="switchIconType(\'builtin\')"> 内置图标' +
        '</label>' +
        '<label style="display:flex;align-items:center;gap:4px;font-size:14px;cursor:pointer;">' +
        '<input type="radio" name="icon_type" value="custom" ' + (currentIconType === 'custom' ? 'checked' : '') + ' onchange="switchIconType(\'custom\')"> 上传自定义' +
        '</label>' +
        '</div>' +
        '<div id="iconBuiltinArea" style="' + (currentIconType === 'builtin' ? '' : 'display:none;') + '">' +
        '<select class="form-select" id="func_icon_select" onchange="updateIconPreview()">' + iconOptions + '</select>' +
        '</div>' +
        '<div id="iconCustomArea" style="' + (currentIconType === 'custom' ? '' : 'display:none;') + '">' +
        '<div style="display:flex;align-items:center;gap:12px;">' +
        '<button class="btn-primary" onclick="uploadIcon()" style="font-size:13px;padding:6px 12px;"><i class="fas fa-upload"></i> 上传图标</button>' +
        '<input type="hidden" id="func_icon_custom" value="' + currentCustomIconUrl + '">' +
        '<span id="icon_upload_status" style="font-size:13px;color:#6b7280;">' + (currentCustomIconUrl ? '已上传' : '未上传') + '</span>' +
        '</div>' +
        '<div class="form-hint">建议尺寸 64x64，支持 png/svg 格式</div>' +
        '</div>' +
        '<div id="iconPreviewArea">' + iconPreview + '</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">页面路径</label>' +
        '<select class="form-select" id="func_page_url">' + pageOptions + '</select>' +
        '<div class="form-hint">内置页面路径，直接选择即可</div>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">外部链接</label>' +
        '<input class="form-input" id="func_ext_url" value="' + extUrl + '" placeholder="如：https://example.com">' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">是否外部链接</label>' +
        '<label class="switch"><input type="checkbox" id="func_is_ext" ' + (isExt ? 'checked' : '') + '><span class="slider"></span></label>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">排序权重</label>' +
        '<input class="form-input" id="func_sort" type="number" value="' + sort + '" placeholder="数字越小越靠前">' +
        '</div>';

    showModal(isEdit ? '编辑菜单' : '新增菜单', body,
        '<button class="btn-secondary" onclick="closeModal()">取消</button>' +
        '<button class="btn-primary" onclick="saveFunction(' + id + ')">保存</button>');
}

function switchIconType(type) {
    currentIconType = type;
    document.getElementById('iconBuiltinArea').style.display = type === 'builtin' ? '' : 'none';
    document.getElementById('iconCustomArea').style.display = type === 'custom' ? '' : 'none';
    updateIconPreview();
}

function updateIconPreview() {
    var previewArea = document.getElementById('iconPreviewArea');
    if (currentIconType === 'builtin') {
        var sel = document.getElementById('func_icon_select');
        previewArea.innerHTML = '<div style="margin-top:8px;font-size:24px;color:#374151;"><i class="fas ' + sel.value + '"></i></div>';
    } else {
        var url = document.getElementById('func_icon_custom').value;
        if (url) {
            previewArea.innerHTML = '<div style="margin-top:8px;"><img src="' + url + '" style="width:32px;height:32px;object-fit:contain;border-radius:4px;"></div>';
        } else {
            previewArea.innerHTML = '<div style="margin-top:8px;font-size:14px;color:#9ca3af;">未上传图标</div>';
        }
    }
}

function uploadIcon() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/png,image/svg+xml,image/jpeg';
    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;
        if (file.size > 500 * 1024) {
            showToast('图标大小不能超过500KB', 'error');
            return;
        }
        var formData = new FormData();
        formData.append('action', 'upload_image');
        formData.append('file', file);
        formData.append('type', 'icon');

        fetch('<?php echo SITE_URL; ?>/admin/api.php', { method: 'POST', body: formData })
        .then(function(res) { return res.json(); })
        .then(function(result) {
            if (result.code === 1) {
                document.getElementById('func_icon_custom').value = result.data.url;
                document.getElementById('icon_upload_status').textContent = '已上传';
                currentCustomIconUrl = result.data.url;
                updateIconPreview();
                showToast('图标上传成功', 'success');
            } else { showToast(result.msg || '上传失败', 'error'); }
        })
        .catch(function() { showToast('上传失败', 'error'); });
    };
    input.click();
}

function editFunction(id) {
    apiRequest('get_function', {id: id}, function(res) {
        if (res.code === 1) {
            showFunctionModal(res.data.id, res.data.category_id, res.data.name, res.data.icon,
                res.data.page_url, res.data.external_url, res.data.is_external, res.data.sort_order);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function saveFunction(id) {
    var cat = document.getElementById('func_cat').value;
    var name = document.getElementById('func_name').value;
    var icon;
    if (currentIconType === 'custom') {
        icon = document.getElementById('func_icon_custom').value;
        if (!icon) { showToast('请上传自定义图标', 'error'); return; }
    } else {
        icon = document.getElementById('func_icon_select').value;
    }
    var pageUrl = document.getElementById('func_page_url').value;
    var extUrl = document.getElementById('func_ext_url').value;
    var isExt = document.getElementById('func_is_ext').checked ? 1 : 0;
    var sort = document.getElementById('func_sort').value;

    if (!cat) { showToast('请选择分类', 'error'); return; }
    if (!name) { showToast('请输入菜单名称', 'error'); return; }

    apiRequest(id > 0 ? 'update_function' : 'create_function', {
        id: id, category_id: cat, name: name, icon: icon,
        page_url: pageUrl, external_url: extUrl, is_external: isExt, sort_order: sort
    }, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function deleteFunction(id) {
    window._deleteFuncId = id;
    confirmAction('确认删除该菜单？', 'doDeleteFunc');
}

function doDeleteFunc() {
    apiRequest('delete_function', {id: window._deleteFuncId}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}
</script>