<?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));
$domains = array();
$error = '';
$success = '';
$batchResults = array();
$menuId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit = $menuId > 0;
$form = array('domain_id' => 0, 'menu_name' => '', 'menu_slug' => '', 'custom_url' => '', 'seo_keywords' => '', 'seo_description' => '', 'show_in_nav' => 1, 'sort_order' => 0, 'is_home' => 0, 'status' => 'enabled');

$homepageDomainIds = array();
$aiModels = array();
try {
    $domains = list_enabled_domain_options();
    $homepageDomainIds = list_domain_ids_with_published_homepage();
    $aiModels = list_enabled_ai_model_options();
    if ($isEdit) {
        $existing = find_menu_by_id($menuId);
        if (!$existing) {
            $error = '未找到对应菜单。';
            $isEdit = false;
        } else {
            $form = array_merge($form, $existing);
        }
    }
} catch (Exception $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    if ($isEdit) {
        $form = normalize_menu_data($_POST);
        try {
            update_menu($menuId, $form);
            $success = '菜单已保存成功。';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    } else {
        $form['menu_name'] = isset($_POST['menu_name']) ? trim((string)$_POST['menu_name']) : '';
        $form['menu_slug'] = isset($_POST['menu_slug']) ? trim((string)$_POST['menu_slug']) : '';
        $form['custom_url'] = isset($_POST['custom_url']) ? trim((string)$_POST['custom_url']) : '';
        $form['seo_keywords'] = isset($_POST['seo_keywords']) ? trim((string)$_POST['seo_keywords']) : '';
        $form['seo_description'] = isset($_POST['seo_description']) ? trim((string)$_POST['seo_description']) : '';
        $form['show_in_nav'] = !empty($_POST['show_in_nav']) ? 1 : 0;
        $form['sort_order'] = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 0;
        $form['is_home'] = 0;
        $form['status'] = isset($_POST['status']) ? trim((string)$_POST['status']) : 'enabled';

        $selectedDomainIds = isset($_POST['domain_ids']) && is_array($_POST['domain_ids']) ? $_POST['domain_ids'] : array();
        $selectedDomainIds = array_map('intval', $selectedDomainIds);
        $selectedDomainIds = array_filter($selectedDomainIds, function ($v) { return $v > 0; });

        if (empty($selectedDomainIds)) {
            $error = '请至少选择一个域名。';
        } elseif ($form['menu_name'] === '') {
            $error = '请填写菜单名称。';
        } else {
            $slug = $form['menu_slug'];
            $hasCustomUrl = $form['custom_url'] !== '';
            if ($slug === '' && (int)$form['is_home'] !== 1 && !$hasCustomUrl) {
                $slug = transliterate_tag_slug($form['menu_name']);
            }
            if ($slug === '' && (int)$form['is_home'] !== 1 && !$hasCustomUrl) {
                $slug = 'menu-' . time();
            }
            $form['menu_slug'] = $slug;

            $okCount = 0;
            $skipCount = 0;
            foreach ($selectedDomainIds as $did) {
                $menuData = array(
                    'domain_id' => $did,
                    'menu_name' => $form['menu_name'],
                    'menu_slug' => $form['menu_slug'],
                    'custom_url' => $form['custom_url'],
                    'seo_keywords' => $form['seo_keywords'],
                    'seo_description' => $form['seo_description'],
                    'show_in_nav' => $form['show_in_nav'],
                    'sort_order' => $form['sort_order'],
                    'is_home' => $form['is_home'],
                    'status' => $form['status']
                );
                $domainLabel = '';
                foreach ($domains as $dd) {
                    if ((int)$dd['id'] === $did) {
                        $domainLabel = $dd['domain'];
                        break;
                    }
                }
                try {
                    create_menu($menuData);
                    $batchResults[] = array('domain' => $domainLabel, 'status' => 'ok', 'msg' => '创建成功（slug=' . $form['menu_slug'] . '）');
                    $okCount++;
                } catch (Exception $ex) {
                    $batchResults[] = array('domain' => $domainLabel, 'status' => 'skip', 'msg' => $ex->getMessage() . ' [发送slug=' . $form['menu_slug'] . ', domain_id=' . $did . ']');
                    $skipCount++;
                }
            }
            $success = '批量创建完成：成功 ' . $okCount . ' 个';
            if ($skipCount > 0) $success .= '，跳过 ' . $skipCount . ' 个';
            $success .= '。';
        }
    }
}

if (isset($_GET['created']) && $_GET['created'] === '1' && $success === '') {
    $success = '菜单创建成功。';
}
?><!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); ?> - <?php echo $isEdit ? '编辑菜单' : '新增菜单'; ?></title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .domain-check-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(240px,1fr)); gap:8px; max-height:260px; overflow-y:auto; padding:12px; border:1px solid #e2e8f0; border-radius:12px; background:#f8fafc; }
    .domain-check-item { display:flex; align-items:center; gap:8px; padding:8px 12px; border-radius:8px; font-size:13px; color:#334155; cursor:pointer; transition:background 0.15s; }
    .domain-check-item:hover { background:#e2e8f0; }
    .domain-check-item input { accent-color:#6366f1; }
    .domain-check-toolbar { display:flex; gap:10px; margin-bottom:8px; }
    .domain-check-toolbar button { font-size:12px; padding:4px 12px; border-radius:6px; border:1px solid #e2e8f0; background:#fff; color:#6366f1; cursor:pointer; }
    .domain-check-toolbar button:hover { background:#eff6ff; }
    </style>
</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><?php echo $isEdit ? '编辑菜单' : '批量新增菜单'; ?></h1><p><?php echo $isEdit ? '修改菜单配置、SEO信息与显示设置。' : '选择多个域名一次性创建同名菜单，栏目别名自动转拼音。'; ?></p></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/menu/list.php">返回列表</a></div>
            </header>

            <?php if ($error !== ''): ?>
                <div class="page-card" style="border-left:4px solid #dc2626; margin-bottom:18px;">
                    <div class="card-head"><div><h2 style="color:#dc2626;">保存失败</h2><p><?php echo e($error); ?></p></div></div>
                </div>
            <?php endif; ?>

            <?php if ($success !== ''): ?>
                <div class="page-card" style="border-left:4px solid #22c55e; margin-bottom:18px;">
                    <div class="card-head"><div><h2 style="color:#15803d;">操作成功</h2><p><?php echo e($success); ?></p></div></div>
                    <?php if (!empty($batchResults)): ?>
                    <table class="data-table" style="margin-top:12px;">
                        <thead><tr><th>域名</th><th>结果</th><th>说明</th></tr></thead>
                        <tbody>
                        <?php foreach ($batchResults as $r): ?>
                            <tr>
                                <td><code><?php echo e($r['domain']); ?></code></td>
                                <td><?php echo $r['status'] === 'ok' ? '<span style="color:#15803d;">✓ 成功</span>' : '<span style="color:#d97706;">⊘ 跳过</span>'; ?></td>
                                <td><?php echo e($r['msg']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                    <div class="filter-row" style="margin-top:14px;">
                        <a class="btn-primary" href="/admin/menu/edit.php">继续新增</a>
                        <a class="btn-soft" href="/admin/menu/list.php">返回列表</a>
                    </div>
                </div>
            <?php endif; ?>

            <section class="page-card">
                <form method="post" action="/admin/menu/edit.php<?php echo $isEdit ? '?id=' . $menuId : ''; ?>">
                    <?php echo csrf_field(); ?>
                    <div class="form-grid">

                        <?php if ($isEdit): ?>
                            <div class="input-group">
                                <span>* 所属域名</span>
                                <select class="select" name="domain_id">
                                    <option value="0">请选择域名</option>
                                    <?php foreach ($domains as $item): ?>
                                        <option value="<?php echo (int)$item['id']; ?>" data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>"<?php echo (int)$form['domain_id'] === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['domain']); ?>（<?php echo e($item['site_name']); ?>）</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php else: ?>
                            <div class="input-group" style="grid-column:1/-1;">
                                <span>* 选择域名（可多选）</span>
                                <div class="domain-check-toolbar">
                                    <button type="button" onclick="document.querySelectorAll('.domain-check-item input').forEach(function(c){c.checked=true;})">全选</button>
                                    <button type="button" onclick="document.querySelectorAll('.domain-check-item input').forEach(function(c){c.checked=false;})">全不选</button>
                                    <button type="button" onclick="document.querySelectorAll('.domain-check-item input').forEach(function(c){c.checked=!c.checked;})">反选</button>
                                </div>
                                <div class="domain-check-grid">
                                    <?php foreach ($domains as $item): ?>
                                        <label class="domain-check-item">
                                            <input type="checkbox" name="domain_ids[]" value="<?php echo (int)$item['id']; ?>" data-language="<?php echo e(isset($item['site_language']) ? $item['site_language'] : 'zh-CN'); ?>">
                                            <?php echo e($item['domain']); ?><small style="color:#94a3b8;">（<?php echo e($item['site_name']); ?>）</small><?php if (isset($homepageDomainIds[(int)$item['id']])): ?><small style="color:#15803d;font-weight:600;"> ✓首页</small><?php endif; ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="input-group" style="grid-column:1/-1;">
                                <span>AI 上下文域名 <small style="color:#94a3b8;">（用于决定 AI 生成语言）</small></span>
                                <select class="select" id="aiContextDomainId">
                                    <option value="0">自动使用首个已选域名</option>
                                    <?php foreach ($domains as $item): ?>
                                        <option value="<?php echo (int)$item['id']; ?>"><?php echo e($item['domain']); ?>（<?php echo e($item['site_name']); ?>）</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php endif; ?>

                        <div class="input-group">
                            <span>* 菜单名称</span>
                            <input class="input" type="text" name="menu_name" id="menuName" value="<?php echo e($form['menu_name']); ?>" placeholder="如：新闻资讯">
                        </div>
                        <div class="input-group">
                            <span>栏目别名 <small style="color:#94a3b8;">（留空自动转拼音）</small></span>
                            <input class="input" type="text" name="menu_slug" id="menuSlug" value="<?php echo e($form['menu_slug']); ?>" placeholder="自动生成，如 xinwen-zixun">
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>自定义链接 <small style="color:#94a3b8;">（填写后菜单指向该链接，栏目别名可留空）</small></span>
                            <input class="input" type="text" name="custom_url" id="customUrl" value="<?php echo e(isset($form['custom_url']) ? $form['custom_url'] : ''); ?>" placeholder="如：https://example.com 或 /some-path">
                            <div style="font-size:12px; color:#94a3b8; margin-top:4px;">填写自定义链接后，该菜单仅作为导航链接使用，不会生成栏目页，也不可被文章生成任务选择。</div>
                        </div>
                        <div class="input-group">
                            <span>排序值</span>
                            <input class="input" type="number" name="sort_order" value="<?php echo (int)$form['sort_order']; ?>">
                        </div>
                        <div class="input-group">
                            <span>导航显示</span>
                            <label style="display:flex; align-items:center; gap:10px; min-height:44px; color:#334155;">
                                <input type="checkbox" name="show_in_nav" value="1"<?php echo !empty($form['show_in_nav']) ? ' checked' : ''; ?>> 在前台导航显示
                            </label>
                        </div>
                        <?php if ($isEdit): ?>
                        <div class="input-group">
                            <span>设为首页菜单</span>
                            <label style="display:flex; align-items:center; gap:10px; min-height:44px; color:#334155;">
                                <input type="checkbox" name="is_home" value="1"<?php echo !empty($form['is_home']) ? ' checked' : ''; ?>> 作为默认首页菜单
                            </label>
                        </div>
                        <?php endif; ?>
                        <div class="input-group">
                            <span>状态</span>
                            <select class="select" name="status">
                                <?php foreach (menu_status_options() as $key => $label): ?>
                                    <option value="<?php echo e($key); ?>"<?php echo $form['status'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>SEO 关键词 & 描述 — AI 生成</span>
                            <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:10px;">
                                <select class="select" id="seoAiModel" style="flex:1;min-width:0;height:40px;margin:0;font-size:13px;padding:4px 8px;">
                                    <?php if (empty($aiModels)): ?>
                                        <option value="">暂无可用模型</option>
                                    <?php else: ?>
                                        <?php foreach ($aiModels as $m): ?>
                                            <option value="<?php echo (int)$m['id']; ?>"><?php echo e($m['provider'] . ' / ' . $m['name']); ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <button type="button" class="btn-soft" id="btnAiSeo" style="white-space:nowrap;height:40px;">AI 生成 SEO</button>
                                <span id="seoAiStatus" style="font-size:13px;color:#6b7280;"></span>
                            </div>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>SEO 关键词</span>
                            <input class="input" type="text" name="seo_keywords" id="seoKeywords" value="<?php echo e($form['seo_keywords']); ?>" placeholder="如：企业资讯,行业新闻,产品动态">
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>SEO 描述</span>
                            <textarea class="input" name="seo_description" id="seoDescription" rows="3" placeholder="栏目页描述，建议 60-120 中文字符。"><?php echo e($form['seo_description']); ?></textarea>
                        </div>
                    </div>
                    <div class="filter-row" style="margin-top:18px;">
                        <button class="btn-primary" type="submit"><?php echo $isEdit ? '保存菜单' : '批量创建'; ?></button>
                        <a class="btn-ghost" href="/admin/menu/list.php">取消</a>
                    </div>
                </form>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
var csrfToken = <?php echo json_encode(csrf_token()); ?>;
(function(){
    var nameInput = document.getElementById('menuName');
    var slugInput = document.getElementById('menuSlug');
    if (!nameInput || !slugInput) return;
    var userEdited = slugInput.value.trim() !== '';
    slugInput.addEventListener('input', function(){ userEdited = this.value.trim() !== ''; });
    nameInput.addEventListener('blur', function(){
        if (userEdited) return;
        var val = this.value.trim();
        if (val === '') return;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/admin/api/slug.php?text=' + encodeURIComponent(val), true);
        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.slug) slugInput.value = data.slug;
                } catch(e){}
            }
        };
        xhr.send();
    });
})();

// AI 生成 SEO 关键词和描述
(function(){
    var btn = document.getElementById('btnAiSeo');
    var status = document.getElementById('seoAiStatus');
    var modelSel = document.getElementById('seoAiModel');
    var kwInput = document.getElementById('seoKeywords');
    var descInput = document.getElementById('seoDescription');
    var nameInput = document.getElementById('menuName');
    if (!btn || !nameInput) return;

    var isHomeCheck = document.querySelector('input[name="is_home"]');
    var domainSelect = document.querySelector('select[name="domain_id"]');
    var aiContextSelect = document.getElementById('aiContextDomainId');
    var aiDomainInputs = document.querySelectorAll('input[name="domain_ids[]"]');

    function getAiContextDomainId() {
        if (aiContextSelect && aiContextSelect.value && aiContextSelect.value !== '0') {
            return aiContextSelect.value;
        }
        if (domainSelect && domainSelect.value && domainSelect.value !== '0') {
            return domainSelect.value;
        }
        for (var i = 0; i < aiDomainInputs.length; i++) {
            if (aiDomainInputs[i].checked) {
                return aiDomainInputs[i].value;
            }
        }
        return '';
    }
    var domainCheckboxes = Array.prototype.slice.call(document.querySelectorAll('input[name="domain_ids[]"]'));

    function getSelectedDomainLanguage() {
        var selected = 'zh-CN';
        var contextSelect = document.getElementById('aiContextDomainId');
        if (contextSelect && contextSelect.value && contextSelect.value !== '0') {
            for (var c = 0; c < domainCheckboxes.length; c++) {
                if (domainCheckboxes[c].value === contextSelect.value) {
                    var ctxLang = domainCheckboxes[c].getAttribute('data-language');
                    if (ctxLang) return ctxLang;
                }
            }
        }
        if (domainSelect && domainSelect.options && domainSelect.selectedIndex >= 0) {
            var optLang = domainSelect.options[domainSelect.selectedIndex].getAttribute('data-language');
            if (optLang) return optLang;
        }
        for (var i = 0; i < domainCheckboxes.length; i++) {
            if (domainCheckboxes[i].checked) {
                var boxLang = domainCheckboxes[i].getAttribute('data-language');
                if (boxLang) return boxLang;
            }
        }
        return selected;
    }

    function getSelectedDomainId() {
        var contextSelect = document.getElementById('aiContextDomainId');
        if (contextSelect && contextSelect.value && contextSelect.value !== '0') {
            return contextSelect.value;
        }
        if (domainSelect && domainSelect.value) {
            return domainSelect.value;
        }
        for (var i = 0; i < domainCheckboxes.length; i++) {
            if (domainCheckboxes[i].checked && domainCheckboxes[i].value) {
                return domainCheckboxes[i].value;
            }
        }
        return '';
    }

    btn.addEventListener('click', function(){
        var menuName = nameInput.value.trim();
        if (!menuName) { alert('请先填写菜单名称'); nameInput.focus(); return; }
        var modelId = modelSel ? modelSel.value : '';
        if (!modelId) { alert('请先配置并启用 AI 模型'); return; }

        var keyword = menuName;
        var domainId = getSelectedDomainId();
        var siteLang = getSelectedDomainLanguage();
        if (isHomeCheck && isHomeCheck.checked) {
            var contextSelect = document.getElementById('aiContextDomainId');
            var targetOpt = null;
            if (contextSelect && contextSelect.value && contextSelect.value !== '0' && domainSelect) {
                targetOpt = domainSelect.options[domainSelect.selectedIndex];
            } else if (domainSelect) {
                targetOpt = domainSelect.options[domainSelect.selectedIndex];
            }
            if (targetOpt) {
                var m = targetOpt.textContent.match(/（(.+?)）/);
                if (m && m[1]) { keyword = m[1]; }
            }
        }

        btn.disabled = true;
        btn.textContent = 'AI 生成中…';
        status.textContent = '';

        var fd = new FormData();
        fd.append('_csrf_token', csrfToken);
        fd.append('menu_name', keyword);
        fd.append('model_id', modelId);
        fd.append('site_language', siteLang);
        if (domainId) { fd.append('domain_id', domainId); }
        if (isHomeCheck && isHomeCheck.checked) { fd.append('is_home', '1'); }

        fetch('/admin/api/ai-generate-menu-seo.php', { method:'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(data){
                if (data.error) {
                    status.textContent = data.error;
                    status.style.color = '#dc2626';
                } else {
                    if (data.keywords) kwInput.value = data.keywords;
                    if (data.description) descInput.value = data.description;
                    status.textContent = '✓ 已生成';
                    status.style.color = '#15803d';
                }
            })
            .catch(function(){
                status.textContent = '请求失败，请检查网络';
                status.style.color = '#dc2626';
            })
            .finally(function(){
                btn.disabled = false;
                btn.textContent = 'AI 生成 SEO';
            });
    });
})();
</script>
</body>
</html>
