<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
$domainId = isset($_GET['domain_id']) ? (int)$_GET['domain_id'] : 0;
$status = isset($_GET['status']) ? trim((string)$_GET['status']) : '';
$deleteStatus = isset($_GET['delete_status']) ? trim((string)$_GET['delete_status']) : '';
$domains = array();
$menus = array();
$dbError = '';

try {
    $domains = list_enabled_domain_options();
    foreach ($domains as $item) {
        ensure_default_home_menu_exists((int)$item['id']);
    }
    $menus = list_menus($domainId, $status);
} catch (Exception $e) {
    $dbError = $e->getMessage();
}
?><!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 e(APP_NAME); ?> - 菜单管理</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('menus', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>菜单管理</h1><p>维护站点导航菜单、栏目页 SEO 信息与显示顺序。</p></div>
                <div class="topbar-actions"><a class="btn-primary" href="/admin/menu/edit.php">新增菜单</a></div>
            </header>
            <section class="page-card">
                <?php if ($deleteStatus === 'success'): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);"><strong style="color:#15803d;">删除成功</strong><p style="margin:0; color:#166534;">菜单已删除。</p></div><?php endif; ?>
                <?php if ($deleteStatus === 'error'): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">删除失败</strong><p style="margin:0; color:#b91c1c;">请稍后重试。</p></div><?php endif; ?>
                <?php if ($dbError !== ''): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">读取失败</strong><p style="margin:0; color:#b91c1c;"><?php echo e($dbError); ?></p></div><?php endif; ?>
                <form class="filter-row" method="get" action="/admin/menu/list.php" style="margin-bottom:16px;">
                    <select class="select" name="domain_id"><option value="0">全部域名</option><?php foreach ($domains as $item): ?><option value="<?php echo (int)$item['id']; ?>"<?php echo $domainId === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['domain']); ?>（<?php echo e($item['site_name']); ?>）</option><?php endforeach; ?></select>
                    <select class="select" name="status"><option value="all">全部状态</option><?php foreach (menu_status_options() as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $status === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select>
                    <button class="btn-soft" type="submit">筛选</button>
                    <a class="btn-ghost" href="/admin/menu/list.php">重置</a>
                </form>
                <form id="batchDeleteForm" method="post" action="/admin/menu/delete.php" style="margin-bottom:12px; display:none;">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="batch" value="1">
                    <button type="submit" class="btn-soft" style="color:#dc2626; border-color:#dc2626;" onclick="return confirm('确认批量删除选中的菜单吗？首页菜单将被跳过。')">批量删除选中项</button>
                </form>
                <table class="data-table">
                    <thead><tr><th><input type="checkbox" id="checkAll"></th><th>ID</th><th>域名</th><th>菜单名称</th><th>栏目路径</th><th>导航显示</th><th>首页菜单</th><th>排序</th><th>状态</th><th>操作</th></tr></thead>
                    <tbody>
                    <?php if (!empty($menus)): ?>
                        <?php foreach ($menus as $item): ?>
                            <tr>
                                <td><input type="checkbox" class="menu-check" value="<?php echo (int)$item['id']; ?>" data-is-home="<?php echo !empty($item['is_home']) ? '1' : '0'; ?>"></td>
                                <td><?php echo (int)$item['id']; ?></td>
                                <td><?php echo e(isset($item['domain_name']) ? $item['domain_name'] : ''); ?></td>
                                <td><strong><?php echo e($item['menu_name']); ?></strong><br><small style="color:#94a3b8;"><?php echo e($item['seo_description']); ?></small></td>
                                <td><?php if (isset($item['custom_url']) && trim((string)$item['custom_url']) !== ''): ?><span style="color:#6366f1;" title="<?php echo e($item['custom_url']); ?>">自定义链接 ↗</span><?php elseif (!empty($item['is_home'])): ?>/<?php else: ?>/<?php echo e($item['menu_slug']); ?>/<?php endif; ?></td>
                                <td><?php echo !empty($item['show_in_nav']) ? '显示' : '隐藏'; ?></td>
                                <td><?php echo !empty($item['is_home']) ? '是' : '否'; ?></td>
                                <td><?php echo (int)$item['sort_order']; ?></td>
                                <td><?php echo e(isset(menu_status_options()[$item['status']]) ? menu_status_options()[$item['status']] : $item['status']); ?></td>
                                <td><a href="/admin/menu/edit.php?id=<?php echo (int)$item['id']; ?>">编辑</a><?php
                                    $canDelete = empty($item['is_home']) || empty($item['domain_name']);
                                    if ($canDelete): ?> / <form method="post" action="/admin/menu/delete.php" style="display:inline;" onsubmit="return confirm('确认删除菜单「<?php echo e($item['menu_name']); ?>」吗？');"><?php echo csrf_field(); ?><input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>"><button type="submit" class="link-btn" style="color:#dc2626;">删除</button></form><?php endif; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="10" class="empty-note"><?php echo $dbError === '' ? '暂无菜单。' : '无法加载菜单数据。'; ?></td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function(){
    var checkAll = document.getElementById('checkAll');
    var batchForm = document.getElementById('batchDeleteForm');
    var checks = document.querySelectorAll('.menu-check');
    function syncBatchForm() {
        var old = batchForm.querySelectorAll('input[name="ids[]"]');
        for (var i = 0; i < old.length; i++) old[i].remove();
        var count = 0;
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                var inp = document.createElement('input');
                inp.type = 'hidden'; inp.name = 'ids[]'; inp.value = checks[i].value;
                batchForm.appendChild(inp);
                count++;
            }
        }
        batchForm.style.display = count > 0 ? '' : 'none';
    }
    if (checkAll) {
        checkAll.addEventListener('change', function() {
            for (var i = 0; i < checks.length; i++) checks[i].checked = this.checked;
            syncBatchForm();
        });
    }
    for (var i = 0; i < checks.length; i++) {
        checks[i].addEventListener('change', syncBatchForm);
    }
})();
</script>
</body>
</html>
