<?php
ob_start();
/**
 * 2026企业CMS - 后台导航菜单管理
 */
require_once __DIR__ . '/header.php';
check_permission('admin');
$pageTitle = '导航菜单管理';
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
    db_exec("DELETE FROM `menus` WHERE `id`=?", [$id]);
    add_log('delete', 'menus', '删除菜单项');
    header('Location: /admin/menus.php?msg=' . urlencode('删除成功！'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    $name = trim($_POST['name'] ?? '');
    $url = trim($_POST['url'] ?? '');
    $position = $_POST['position'] ?? 'header';
    $sortOrder = intval($_POST['sort_order'] ?? 0);
    
    if ($action === 'add') {
        db_exec("INSERT INTO `menus` (`name`,`url`,`position`,`sort_order`) VALUES (?,?,?,?)",
            [$name, $url, $position, $sortOrder]);
        add_log('add', 'menus', '添加菜单: ' . $name);
    } elseif ($action === 'edit' && $id) {
        db_exec("UPDATE `menus` SET `name`=?,`url`=?,`position`=?,`sort_order`=? WHERE `id`=?",
            [$name, $url, $position, $sortOrder, $id]);
        add_log('edit', 'menus', '编辑菜单: ' . $name);
    }
    header('Location: /admin/menus.php?msg=' . urlencode('保存成功！'));
    exit;
}

$menu = [];
if ($action === 'add' || ($action === 'edit' && $id)) {
    if ($id) $menu = db_query_one("SELECT * FROM `menus` WHERE `id`=?", [$id]);
?>
<div class="page-header">
    <h2><?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")=='add'?'添加菜单项':'编辑菜单项'; ?></h2>
    <a href="/admin/menus.php" class="btn">← 返回列表</a>
</div>
<div class="form-card">
    <form method="post" action="">
        <?php echo csrf_input(); ?>
        <div class="form-row">
            <div class="form-group">
                <label>菜单名称 <span style="color:red;">*</span></label>
                <input type="text" name="name" value="<?php echo xss_clean($menu['name'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label>菜单位置</label>
                <select name="position">
                    <option value="header" <?php echo ($menu['position']??'header')=='header'?'selected':''; ?>>顶部导航</option>
                    <option value="footer" <?php echo ($menu['position']??'')=='footer'?'selected':''; ?>>底部导航</option>
                </select>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group" style="flex:2;">
                <label>链接地址 <span style="color:red;">*</span></label>
                <input type="text" name="url" value="<?php echo xss_clean($menu['url'] ?? ''); ?>" required placeholder="如: /about.html 或 https://...">
                <div class="hint">站内链接以 / 开头，外部链接填写完整URL</div>
            </div>
            <div class="form-group">
                <label>排序</label>
                <input type="number" name="sort_order" value="<?php echo $menu['sort_order'] ?? 0; ?>">
            </div>
        </div>
        <div style="margin-top:30px;">
            <button type="submit" name="save" class="btn btn-primary" style="margin-right:10px;">保存</button>
            <a href="/admin/menus.php" class="btn">取消</a>
        </div>
    </form>
</div>
<?php
require_once __DIR__ . '/footer.php';
exit;
}

// 列表
$positionFilter = $_GET['position'] ?? '';
$where = '1=1';
$params = [];
if ($positionFilter) {
    $where .= ' AND `position`=?';
    $params[] = $positionFilter;
}
$menus = db_query("SELECT * FROM `menus` WHERE {$where} ORDER BY `position` ASC, `sort_order` ASC", $params);
?>
<div class="page-header">
    <h2>导航菜单管理</h2>
    <a href="/admin/menus.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 添加菜单</a>
</div>

<form method="get" class="search-bar" style="max-width:300px;margin-bottom:20px;">
    <select name="position" onchange="this.form.submit()" style="padding:8px;border:1px solid #ddd;border-radius:4px;">
        <option value="">全部位置</option>
        <option value="header" <?php echo $positionFilter=='header'?'selected':''; ?>>顶部导航</option>
        <option value="footer" <?php echo $positionFilter=='footer'?'selected':''; ?>>底部导航</option>
    </select>
</form>

<div class="table-wrapper">
    <table>
        <thead><tr><th>ID</th><th>名称</th><th>链接</th><th>位置</th><th>排序</th><th>操作</th></tr></thead>
        <tbody>
            <?php foreach ($menus as $m): ?>
            <tr>
                <td><?php echo $m['id']; ?></td>
                <td><?php echo xss_clean($m['name']); ?></td>
                <td><a href="<?php echo xss_clean($m['url']); ?>" target="_blank" style="font-size:13px;"><?php echo xss_clean($m['url']); ?></a></td>
                <td><?php echo $m['position']=='header'?'<span class="badge badge-success">顶部</span>':'<span class="badge">底部</span>'; ?></td>
                <td><?php echo $m['sort_order']; ?></td>
                <td class="actions">
                    <a href="/admin/menus.php?action=edit&id=<?php echo $m['id']; ?>" class="btn btn-sm btn-primary">编辑</a>
                    <a href="javascript:void(0)" onclick="if(confirmDelete(<?php echo $m['id']; ?>,'<?php echo xss_clean($m['name']); ?>')){location.href='/admin/menus.php?action=delete&id=<?php echo $m['id']; ?>'}" class="btn btn-sm btn-danger">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<div class="form-card" style="margin-top:20px;">
    <h3 style="margin-bottom:10px;font-size:14px;color:#999;">常用链接参考</h3>
    <div style="display:flex;flex-wrap:wrap;gap:8px;">
        <?php $refs = [['首页','/'],['关于我们','/about.html'],['产品中心','/products.html'],['新闻资讯','/news.html'],['成功案例','/cases.html'],['联系我们','/contact.html'],['服务内容','/services.html'],['团队成员','/team.html']]; ?>
        <?php foreach ($refs as $r): ?>
        <code style="padding:3px 8px;background:#f5f5f5;border-radius:3px;font-size:12px;"><?php echo $r[1]; ?> - <?php echo $r[0]; ?></code>
        <?php endforeach; ?>
    </div>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
