<?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));
$statusOptions = content_status_options();
$domains = list_enabled_domain_options();
$menuOptions = array();
$error = '';
$success = '';
ensure_template_packs_dir();
initialize_builtin_template_packs();
$pageTemplateOptions = list_template_packs_by_type('page');
$contentId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$created = isset($_GET['created']) ? true : false;
$content = $contentId > 0 ? find_content_by_id($contentId) : null;

if (!$content) {
    redirect('/admin/content/list.php');
}

$contentTemplateId = isset($content['template_id']) ? (int)$content['template_id'] : 0;
$isHomepageTemplate = $contentTemplateId > 0 ? is_homepage_template_id($contentTemplateId) : (isset($content['path']) && in_array((string)$content['path'], array('index', 'home', ''), true));
$publicPathLabel = $isHomepageTemplate ? '/' : '/' . (isset($content['path']) ? (string)$content['path'] : (isset($content['slug']) ? (string)$content['slug'] : ''));
$homepageSchema = homepage_template_variable_schema();
$homepageTemplateVars = decode_template_vars_json(isset($content['template_vars_json']) ? (string)$content['template_vars_json'] : '');
$homepageTemplateVars = $isHomepageTemplate ? array_merge(default_template_vars_for_type('homepage', array(
    'site_name' => isset($content['title']) ? (string)$content['title'] : '',
    'domain' => '',
    'keyword' => isset($content['seo_keywords']) ? (string)$content['seo_keywords'] : '',
    'path' => '/',
    'site_description' => isset($content['seo_description']) ? (string)$content['seo_description'] : ''
)), $homepageTemplateVars) : $homepageTemplateVars;

$form = array(
    'title' => isset($content['title']) ? (string)$content['title'] : '',
    'path' => isset($content['path']) ? (string)$content['path'] : (isset($content['slug']) ? (string)$content['slug'] : ''),
    'domain_id' => isset($content['domain_id']) ? (int)$content['domain_id'] : 0,
    'template_id' => isset($content['template_id']) ? (int)$content['template_id'] : 0,
    'menu_ids' => list_content_menu_ids($contentId),
    'seo_title' => isset($content['seo_title']) ? (string)$content['seo_title'] : '',
    'seo_keywords' => isset($content['seo_keywords']) ? (string)$content['seo_keywords'] : '',
    'seo_description' => isset($content['seo_description']) ? (string)$content['seo_description'] : '',
    'content_body' => isset($content['content_body']) ? (string)$content['content_body'] : '',
    'status' => isset($content['status']) ? (string)$content['status'] : 'draft',
    'remark' => isset($content['remark']) ? (string)$content['remark'] : '',
    'static_file_path' => isset($content['static_file_path']) ? (string)$content['static_file_path'] : '',
    'static_published_at' => isset($content['static_published_at']) ? (string)$content['static_published_at'] : '',
    'page_template_pack' => isset($content['page_template_pack']) ? (string)$content['page_template_pack'] : ''
);
// 预填封面图（可选）
$form['cover_image'] = isset($content['cover_image']) ? (string)$content['cover_image'] : '';

if ($form['domain_id'] > 0) {
    $menuOptions = list_enabled_menu_options($form['domain_id']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $form['title'] = isset($_POST['title']) ? trim((string)$_POST['title']) : '';
    $form['path'] = isset($_POST['path']) ? trim((string)$_POST['path']) : '';
    $form['domain_id'] = isset($_POST['domain_id']) ? (int)$_POST['domain_id'] : 0;
    $form['template_id'] = isset($_POST['template_id']) ? (int)$_POST['template_id'] : 0;
    $form['menu_ids'] = isset($_POST['menu_ids']) && is_array($_POST['menu_ids']) ? array_values(array_unique(array_map('intval', $_POST['menu_ids']))) : array();
    $form['seo_title'] = isset($_POST['seo_title']) ? trim((string)$_POST['seo_title']) : '';
    $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['content_body'] = isset($_POST['content_body']) ? (string)$_POST['content_body'] : '';
    $form['status'] = isset($_POST['status']) ? trim((string)$_POST['status']) : 'draft';
    $form['remark'] = isset($_POST['remark']) ? trim((string)$_POST['remark']) : '';
    $form['page_template_pack'] = isset($_POST['page_template_pack']) ? trim((string)$_POST['page_template_pack']) : '';
    // 接收手动封面图（可选，允许清空）
    if (array_key_exists('cover_image', $_POST)) {
        $form['cover_image'] = trim((string)$_POST['cover_image']);
    }
    if ($form['domain_id'] > 0) {
        $menuOptions = list_enabled_menu_options($form['domain_id']);
    }

    if ($isHomepageTemplate) {
        $postedHomepageVars = isset($_POST['homepage_template_vars']) && is_array($_POST['homepage_template_vars']) ? $_POST['homepage_template_vars'] : array();
        $homepageTemplateVars = sanitize_template_vars_by_schema($postedHomepageVars, 'homepage', array(
            'site_name' => $form['title'],
            'domain' => '',
            'keyword' => $form['seo_keywords'],
            'path' => '/',
            'site_description' => $form['seo_description']
        ));
    }

    try {
        if ($isHomepageTemplate) {
            $form['template_vars'] = $homepageTemplateVars;
        }
        update_content($contentId, $form);
        $success = '内容已保存成功。';
        $content = find_content_by_id($contentId);
        if ($content) {
            $homepageTemplateVars = decode_template_vars_json(isset($content['template_vars_json']) ? (string)$content['template_vars_json'] : '');
            $homepageTemplateVars = $isHomepageTemplate ? array_merge(default_template_vars_for_type('homepage', array(
                'site_name' => isset($content['title']) ? (string)$content['title'] : '',
                'domain' => '',
                'keyword' => isset($content['seo_keywords']) ? (string)$content['seo_keywords'] : '',
                'path' => '/',
                'site_description' => isset($content['seo_description']) ? (string)$content['seo_description'] : ''
            )), $homepageTemplateVars) : $homepageTemplateVars;
            $form = array(
                'title' => isset($content['title']) ? (string)$content['title'] : '',
                'path' => isset($content['path']) ? (string)$content['path'] : (isset($content['slug']) ? (string)$content['slug'] : ''),
                'domain_id' => isset($content['domain_id']) ? (int)$content['domain_id'] : 0,
                'template_id' => isset($content['template_id']) ? (int)$content['template_id'] : 0,
                'menu_ids' => list_content_menu_ids($contentId),
                'seo_title' => isset($content['seo_title']) ? (string)$content['seo_title'] : '',
                'seo_keywords' => isset($content['seo_keywords']) ? (string)$content['seo_keywords'] : '',
                'seo_description' => isset($content['seo_description']) ? (string)$content['seo_description'] : '',
                'content_body' => isset($content['content_body']) ? (string)$content['content_body'] : '',
                'status' => isset($content['status']) ? (string)$content['status'] : 'draft',
                'remark' => isset($content['remark']) ? (string)$content['remark'] : '',
                'static_file_path' => isset($content['static_file_path']) ? (string)$content['static_file_path'] : '',
                'static_published_at' => isset($content['static_published_at']) ? (string)$content['static_published_at'] : ''
            );
            if ($form['domain_id'] > 0) {
                $menuOptions = list_enabled_menu_options($form['domain_id']);
            }
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

if ($created && $success === '' && $error === '') {
    $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); ?> - 编辑内容</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('content', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <form method="post" action="/admin/content/edit.php?id=<?php echo $contentId; ?>">
            <?php echo csrf_field(); ?>
            <header class="topbar"><div><h1>编辑内容</h1><p><?php echo e($form['title']); ?>（<?php echo e($publicPathLabel); ?>）</p></div><div class="topbar-actions"><button class="btn-primary" type="submit">保存内容</button><?php if ($form['status'] === 'published'): ?><a class="btn-soft" href="/admin/content/static-publish.php?id=<?php echo $contentId; ?>">重新静态发布</a><button type="button" class="btn-primary" onclick="if(confirm('确认取消发布吗？')){var f=document.createElement('form');f.method='post';f.action='/admin/content/status.php';f.innerHTML='<input name=_csrf_token value=<?php echo e(csrf_token()); ?>><input name=id value=<?php echo $contentId; ?>><input name=status value=draft>';document.body.appendChild(f);f.submit();}">取消发布</button><?php else: ?><button type="button" class="btn-primary" onclick="if(confirm('确认发布吗？')){var f=document.createElement('form');f.method='post';f.action='/admin/content/status.php';f.innerHTML='<input name=_csrf_token value=<?php echo e(csrf_token()); ?>><input name=id value=<?php echo $contentId; ?>><input name=status value=published>';document.body.appendChild(f);f.submit();}">立即发布</button><?php endif; ?><a class="btn-ghost" href="/admin/content/list.php">返回列表</a></div></header>
                <?php if ($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;"><?php echo e($success); ?></p></div><?php endif; ?>
                <?php if ($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;"><?php echo e($error); ?></p></div><?php endif; ?>
                <?php if ($form['status'] === 'published'): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(79,70,229,0.12); background: rgba(79,70,229,0.04);"><strong style="color:#4338ca;">前台访问</strong><p style="margin:0; color:#3730a3;">当前内容已发布，可通过绑定域名访问 <code><?php echo e($publicPathLabel); ?></code><?php echo $isHomepageTemplate ? '（首页模板固定使用根路径访问）' : ''; ?>；静态文件<?php echo $form['static_file_path'] !== '' ? '已输出到 <code>' . e($form['static_file_path']) . '</code>' : '尚未生成'; ?>。</p></div><?php endif; ?>
                <?php if ($isHomepageTemplate): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(249,115,22,0.16); background: rgba(255,247,237,0.92);"><strong style="color:#c2410c;">首页结构化字段模式</strong><p style="margin:0; color:#9a3412;">当前内容使用固定标签驱动首页模块（无正文编辑器），请在下方直接编辑各区块字段值。</p></div><?php endif; ?>
                <?php if (isset($content['source_type']) && $content['source_type'] === 'article_ai'): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(14,165,233,0.16); background: rgba(240,249,255,0.94);"><strong style="color:#0369a1;">AI文章来源</strong><p style="margin:0; color:#075985;">来源关键词：<?php echo e(isset($content['source_keyword']) && $content['source_keyword'] !== '' ? $content['source_keyword'] : '-'); ?><?php echo (isset($content['cover_image']) && trim((string)$content['cover_image']) !== '') ? ' · 封面图：<code>' . e($content['cover_image']) . '</code>' : ''; ?></p></div><?php endif; ?>
                <input type="hidden" name="template_id" value="<?php echo (int)$form['template_id']; ?>">
                <input type="hidden" name="path" value="<?php echo e($form['path']); ?>">

                <!-- 顶部：基本信息 -->
                <section class="page-card">
                    <div class="card-head"><div><h2>基本信息</h2></div></div>
                    <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                        <div class="input-group" style="grid-column:1/-1;"><span>* 页面标题</span><input class="input" type="text" name="title" value="<?php echo e($form['title']); ?>"></div>
                        <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']; ?>"<?php echo $form['domain_id'] === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['domain']); ?>（<?php echo e($item['site_name']); ?>）</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group"><span>所属菜单</span>
                            <select class="select" name="menu_ids[]" multiple size="4">
                                <?php foreach ($menuOptions as $item): ?>
                                <option value="<?php echo (int)$item['id']; ?>"<?php echo in_array((int)$item['id'], $form['menu_ids'], true) ? ' selected' : ''; ?>><?php echo e($item['menu_name']); ?>（<?php echo !empty($item['is_home']) ? '首页' : e($item['menu_slug']); ?>）</option>
                                <?php endforeach; ?>
                            </select>
                            <div style="font-size:12px; color:#94a3b8; margin-top:6px;">按住 Ctrl 可多选</div>
                        </div>
                        <?php if (!empty($pageTemplateOptions)): ?>
                        <div class="input-group"><span>页面模板</span>
                            <select class="select" name="page_template_pack">
                                <option value="">不使用页面模板（使用域名套件）</option>
                                <?php foreach ($pageTemplateOptions as $pt): $ptCode = isset($pt['code']) ? $pt['code'] : ''; $ptName = isset($pt['name']) ? $pt['name'] : $ptCode; ?>
                                <option value="page:<?php echo e($ptCode); ?>"<?php echo $form['page_template_pack'] === 'page:' . $ptCode ? ' selected' : ''; ?>><?php echo e($ptName); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div style="font-size:12px; color:#94a3b8; margin-top:6px;">选择页面模板后将使用独立页面布局，适用于"关于我们"等独立页面</div>
                        </div>
                        <?php endif; ?>
                    </div>
                </section>

                <?php if ($isHomepageTemplate): ?>
                <!-- 首页模板：单列 -->
                <section class="page-card" style="margin-top:20px;">
                    <div class="card-head"><div><h2>SEO 信息</h2></div><div class="topbar-actions"><button class="btn-soft" type="button" id="aiSeoBtn">AI 生成 SEO</button></div></div>
                    <div id="aiSeoHint" class="mini-item" style="margin-bottom:12px; border-color:rgba(79,70,229,0.18); background:rgba(79,70,229,0.06); display:none;"><strong style="color:#4338ca;">AI SEO 生成</strong><p id="aiSeoHintText" style="margin:0; color:#3730a3;"></p></div>
                    <div class="form-grid"><div class="input-group" style="grid-column:1/-1;"><span>SEO 标题</span><input class="input" type="text" name="seo_title" value="<?php echo e($form['seo_title']); ?>"></div><div class="input-group" style="grid-column:1/-1;"><span>SEO 关键词</span><input class="input" type="text" name="seo_keywords" value="<?php echo e($form['seo_keywords']); ?>"></div><div class="input-group" style="grid-column:1/-1;"><span>SEO 描述</span><textarea class="input" name="seo_description" rows="3"><?php echo e($form['seo_description']); ?></textarea></div></div>
                </section>
                <?php else: ?>
                <!-- 文章模板：二列布局 -->
                <div class="edit-two-col" style="margin-top:20px;">
                <div class="edit-col-left">
                <section class="page-card">
                    <div class="card-head"><div><h2>SEO 信息</h2></div><div class="topbar-actions"><button class="btn-soft" type="button" id="aiSeoBtn">AI 生成 SEO</button></div></div>
                    <div id="aiSeoHint" class="mini-item" style="margin-bottom:12px; border-color:rgba(79,70,229,0.18); background:rgba(79,70,229,0.06); display:none;"><strong style="color:#4338ca;">AI SEO 生成</strong><p id="aiSeoHintText" style="margin:0; color:#3730a3;"></p></div>
                    <div class="form-grid" style="grid-template-columns:1fr;">
                        <div class="input-group"><span>SEO 标题</span><input class="input" type="text" name="seo_title" value="<?php echo e($form['seo_title']); ?>"></div>
                        <div class="input-group"><span>SEO 关键词</span><input class="input" type="text" name="seo_keywords" value="<?php echo e($form['seo_keywords']); ?>"></div>
                        <div class="input-group"><span>SEO 描述</span><textarea class="input" name="seo_description" rows="3"><?php echo e($form['seo_description']); ?></textarea></div>
                        <div class="input-group"><span>封面图 URL（可选）</span>
                            <input class="input" type="text" name="cover_image" value="<?php echo e(isset($form['cover_image']) ? $form['cover_image'] : ''); ?>" placeholder="例如 /uploads/article-covers/202606/xxx.png 或 https://...">
                            <div style="font-size:12px; color:#94a3b8; margin-top:6px;">留空将自动使用正文首张图片；清空后保存可移除封面图。</div>
                        </div>
                        <div class="input-group"><span>状态</span>
                            <select class="select" name="status">
                                <?php foreach ($statusOptions 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"><span>备注</span><input class="input" type="text" name="remark" value="<?php echo e(isset($form['remark']) ? $form['remark'] : ''); ?>"></div>
                    </div>
                </section>
                </div><!-- /edit-col-left -->

                <div class="edit-col-right">
                <section class="page-card">
                    <div class="card-head">
                        <div><h2>正文内容</h2><p>富文本编辑器 · 支持 AI 生成、图片上传、拖拽/粘贴上传，提交时注入模板 <code>{{content}}</code>。</p></div>
                        <div class="topbar-actions"><button class="btn-soft" type="button" id="insertCoverBtn">插入标题图</button><button class="btn-soft" type="button" id="aiGenerateBtn">AI 生成正文</button></div>
                    </div>
                    <div id="aiGenerateHint" class="mini-item" style="margin-bottom:12px; border-color:rgba(79,70,229,0.18); background:rgba(79,70,229,0.06); display:none;"><strong style="color:#4338ca;">AI 正文生成</strong><p id="aiGenerateHintText" style="margin:0; color:#3730a3;">点击按钮后将根据标题自动生成正文并填入编辑器。</p></div>
                    <textarea id="contentBodyEditor" name="content_body" class="rich-editor-source" style="width:100%; min-height:420px;"><?php echo e($form['content_body']); ?></textarea>
                </section>
                <div class="filter-row" style="margin-top:18px;"><button class="btn-primary" type="submit">保存内容</button><a class="btn-ghost" href="/admin/content/list.php">返回</a></div>
                </div><!-- /edit-col-right -->
                </div><!-- /edit-two-col -->
                <?php endif; ?>

                <?php if ($isHomepageTemplate): ?>
                    <section class="page-card" style="margin-top:20px;">
                        <div class="card-head"><div><h2>首页模板变量编辑</h2><p>可直接修改首页各模块字段，保存后系统会回填到模板标签并用于预览与静态发布。</p></div></div>
                        <div class="form-grid">
                            <?php foreach ($homepageSchema as $var => $meta): ?>
                                <?php $fieldType = isset($meta['type']) ? (string)$meta['type'] : 'text'; ?>
                                <?php $fieldValue = isset($homepageTemplateVars[$var]) ? (string)$homepageTemplateVars[$var] : ''; ?>
                                <?php $fieldStyle = $fieldType === 'textarea' ? 'grid-column: 1 / -1;' : ''; ?>
                                <div class="input-group"<?php echo $fieldStyle !== '' ? ' style="' . e($fieldStyle) . '"' : ''; ?>>
                                    <span><?php echo e(isset($meta['label']) ? $meta['label'] : $var); ?></span>
                                    <?php if ($fieldType === 'textarea'): ?>
                                        <textarea class="input" name="homepage_template_vars[<?php echo e($var); ?>]" rows="3" placeholder="<?php echo e($var); ?>"><?php echo e($fieldValue); ?></textarea>
                                    <?php else: ?>
                                        <input class="input" type="text" name="homepage_template_vars[<?php echo e($var); ?>]" value="<?php echo e($fieldValue); ?>" placeholder="<?php echo e($var); ?>">
                                    <?php endif; ?>
                                    <div style="font-size:12px; color:#94a3b8; margin-top:6px;"><code><?php echo e($var); ?></code><?php echo isset($meta['default']) && $meta['default'] !== '' ? ' · 默认值：' . e((string)$meta['default']) : ''; ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <input type="hidden" name="content_body" value="">
                <div class="filter-row" style="margin-top:18px;"><button class="btn-primary" type="submit">保存内容</button><a class="btn-ghost" href="/admin/content/list.php">返回</a></div>
                <?php endif; ?>
            </form>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function () {
    var domainSelect = document.querySelector('select[name="domain_id"]');
    var menuSelect = document.querySelector('select[name="menu_ids[]"]');
    if (!domainSelect || !menuSelect) { return; }
    var selectedMenuIds = Array.prototype.map.call(menuSelect.selectedOptions || [], function (o) { return parseInt(o.value, 10); });
    function loadMenus(domainId) {
        if (!domainId || domainId <= 0) { menuSelect.innerHTML = ''; return; }
        menuSelect.innerHTML = '<option disabled>正在加载菜单…</option>';
        fetch('/admin/menu/by-domain.php?domain_id=' + encodeURIComponent(domainId), { credentials: 'same-origin' })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                menuSelect.innerHTML = '';
                if (!data || !data.ok || !Array.isArray(data.items) || data.items.length === 0) {
                    var empty = document.createElement('option');
                    empty.disabled = true; empty.textContent = '当前域名尚未配置启用菜单';
                    menuSelect.appendChild(empty);
                    return;
                }
                data.items.forEach(function (item) {
                    var opt = document.createElement('option');
                    opt.value = item.id;
                    opt.textContent = item.menu_name + '（' + (item.is_home ? '首页' : item.menu_slug) + '）';
                    if (selectedMenuIds.indexOf(item.id) !== -1) { opt.selected = true; }
                    menuSelect.appendChild(opt);
                });
            })
            .catch(function () {
                menuSelect.innerHTML = '<option disabled>菜单加载失败，请重试</option>';
            });
    }
    domainSelect.addEventListener('change', function () {
        selectedMenuIds = [];
        loadMenus(parseInt(domainSelect.value, 10));
    });
})();
</script>
<?php if (!$isHomepageTemplate): ?>
<script src="https://cdn.ckeditor.com/4.22.1/standard-all/ckeditor.js"></script>
<script>
(function () {
    if (typeof CKEDITOR === 'undefined') { return; }
    CKEDITOR.replace('contentBodyEditor', {
        language: 'zh-cn',
        height: 480,
        versionCheck: false,
        removePlugins: 'elementspath',
        resize_enabled: true,
        extraPlugins: 'justify,colorbutton,colordialog',
        toolbar: [
            { name: 'document', items: ['Source', '-', 'Maximize'] },
            { name: 'clipboard', items: ['Undo', 'Redo'] },
            { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat'] },
            { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'JustifyLeft', 'JustifyCenter', 'JustifyRight'] },
            { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
            { name: 'insert', items: ['Image', 'Table', 'HorizontalRule', 'SpecialChar'] },
            { name: 'styles', items: ['Format', 'FontSize'] },
            { name: 'colors', items: ['TextColor', 'BGColor'] }
        ],
        contentsCss: ['/assets/css/admin-ui.css'],
        allowedContent: true,
        filebrowserUploadUrl: '/admin/api/editor-upload-image.php?domain_id=0',
        filebrowserImageUploadUrl: '/admin/api/editor-upload-image.php?domain_id=0',
        filebrowserUploadMethod: 'xhr',
        uploadUrl: '/admin/api/editor-upload-image.php?domain_id=0',
        imageUploadUrl: '/admin/api/editor-upload-image.php?domain_id=0',
        extraAllowedContent: 'img[!src,alt,width,height,style]'
    });

    function refreshUploadUrl() {
        var ed = CKEDITOR.instances.contentBodyEditor;
        var sel = document.querySelector('select[name="domain_id"]');
        if (!ed || !sel) { return; }
        var id = parseInt(sel.value, 10) || 0;
        var u = '/admin/api/editor-upload-image.php?domain_id=' + id;
        ed.config.filebrowserUploadUrl = u;
        ed.config.filebrowserImageUploadUrl = u;
        ed.config.uploadUrl = u;
        ed.config.imageUploadUrl = u;
    }
    var domainSel = document.querySelector('select[name="domain_id"]');
    if (domainSel) {
        domainSel.addEventListener('change', refreshUploadUrl);
        if (window.CKEDITOR && CKEDITOR.instances.contentBodyEditor) {
            CKEDITOR.instances.contentBodyEditor.on('instanceReady', refreshUploadUrl);
        }
    }
})();
</script>
<script>
(function () {
    var btn = document.getElementById('aiGenerateBtn');
    var hint = document.getElementById('aiGenerateHint');
    var hintText = document.getElementById('aiGenerateHintText');
    if (!btn) { return; }
    function showHint(msg, color) {
        if (!hint || !hintText) { return; }
        hint.style.display = 'block';
        hintText.textContent = msg;
        hintText.style.color = color || '#3730a3';
    }
    btn.addEventListener('click', function () {
        var titleInput = document.querySelector('input[name="title"]');
        var keywordsInput = document.querySelector('input[name="seo_keywords"]');
        var title = titleInput ? titleInput.value.trim() : '';
        var keywords = keywordsInput ? keywordsInput.value.trim() : '';
        if (!title) {
            showHint('请先填写页面标题再点击 AI 生成。', '#b91c1c');
            if (titleInput) { titleInput.focus(); }
            return;
        }
        if (!window.CKEDITOR || !CKEDITOR.instances || !CKEDITOR.instances.contentBodyEditor) {
            showHint('编辑器尚未就绪，请稍后重试。', '#b91c1c');
            return;
        }
        btn.disabled = true;
        var originalText = btn.textContent;
        btn.textContent = '生成中…';
        showHint('正在调用 AI 模型生成正文，大约需要 10-60 秒，请耐心等待…', '#3730a3');
        var form = new FormData();
        form.append('title', title);
        form.append('keywords', keywords);
        fetch('/admin/api/editor-ai-generate.php', { method: 'POST', body: form, credentials: 'same-origin' })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data || !data.ok) { throw new Error(data && data.error ? data.error : 'AI 生成失败'); }
                CKEDITOR.instances.contentBodyEditor.setData(data.html);
                var modelName = (data.model && data.model.name) ? data.model.name : '';
                showHint('已生成正文' + (modelName ? '（模型：' + modelName + '）' : '') + '，请检查并编辑后再保存。', '#15803d');
            })
            .catch(function (err) {
                showHint('AI 生成失败：' + (err && err.message ? err.message : err), '#b91c1c');
            })
            .then(function () {
                btn.disabled = false;
                btn.textContent = originalText;
            });
    });
})();
</script>
<?php endif; ?>
<script>
(function () {
    var btn = document.getElementById('aiSeoBtn');
    if (!btn) { return; }
    var hint = document.getElementById('aiSeoHint');
    var hintText = document.getElementById('aiSeoHintText');
    function showSeoHint(msg, color) {
        if (!hint || !hintText) { return; }
        hint.style.display = 'block';
        hintText.textContent = msg;
        hintText.style.color = color || '#3730a3';
    }
    btn.addEventListener('click', function () {
        var titleInput = document.querySelector('input[name="title"]');
        var title = titleInput ? titleInput.value.trim() : '';
        if (!title) {
            showSeoHint('请先填写页面标题再生成 SEO 信息。', '#b91c1c');
            if (titleInput) { titleInput.focus(); }
            return;
        }
        btn.disabled = true;
        var originalText = btn.textContent;
        btn.textContent = '生成中…';
        showSeoHint('正在调用 AI 模型生成 SEO 信息，请稍候…', '#3730a3');
        var form = new FormData();
        form.append('title', title);
        fetch('/admin/api/editor-ai-generate-seo.php', { method: 'POST', body: form, credentials: 'same-origin' })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data || !data.ok) { throw new Error(data && data.error ? data.error : 'AI 生成失败'); }
                var st = document.querySelector('input[name="seo_title"]');
                var sk = document.querySelector('input[name="seo_keywords"]');
                var sd = document.querySelector('[name="seo_description"]');
                if (st) { st.value = data.seo_title || ''; }
                if (sk) { sk.value = data.seo_keywords || ''; }
                if (sd) { sd.value = data.seo_description || ''; }
                var modelName = (data.model && data.model.name) ? data.model.name : '';
                showSeoHint('SEO 信息已生成' + (modelName ? '（模型：' + modelName + '）' : '') + '，请检查后保存。', '#15803d');
            })
            .catch(function (err) {
                showSeoHint('AI 生成失败：' + (err && err.message ? err.message : err), '#b91c1c');
            })
            .then(function () {
                btn.disabled = false;
                btn.textContent = originalText;
            });
    });
})();
</script>
<?php if (!$isHomepageTemplate): ?>
<script>
(function () {
    var btn = document.getElementById('insertCoverBtn');
    if (!btn) { return; }
    var hint = document.getElementById('aiGenerateHint');
    var hintText = document.getElementById('aiGenerateHintText');
    function showCoverHint(msg, color) {
        if (!hint || !hintText) { return; }
        hint.style.display = 'block';
        hintText.textContent = msg;
        hintText.style.color = color || '#3730a3';
    }
    btn.addEventListener('click', function () {
        var titleInput = document.querySelector('input[name="title"]');
        var title = titleInput ? titleInput.value.trim() : '';
        if (!title) {
            showCoverHint('请先填写页面标题再生成标题图。', '#b91c1c');
            if (titleInput) { titleInput.focus(); }
            return;
        }
        if (!window.CKEDITOR || !CKEDITOR.instances || !CKEDITOR.instances.contentBodyEditor) {
            showCoverHint('编辑器尚未就绪，请稍后重试。', '#b91c1c');
            return;
        }
        btn.disabled = true;
        var originalText = btn.textContent;
        btn.textContent = '生成中…';
        showCoverHint('正在生成标题图，请稍候…', '#3730a3');
        var form = new FormData();
        form.append('title', title);
        fetch('/admin/api/editor-generate-cover.php', { method: 'POST', body: form, credentials: 'same-origin' })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data || !data.ok) { throw new Error(data && data.error ? data.error : '生成失败'); }
                var imgHtml = '<p><img src="' + data.url + '" alt="' + title.replace(/"/g, '&quot;') + '" style="max-width:100%; height:auto; border-radius:12px;"></p>';
                var editor = CKEDITOR.instances.contentBodyEditor;
                var existing = editor.getData();
                editor.setData(imgHtml + '\n' + existing);
                showCoverHint('标题图已插入到正文开头，请检查后保存。', '#15803d');
            })
            .catch(function (err) {
                showCoverHint('标题图生成失败：' + (err && err.message ? err.message : err), '#b91c1c');
            })
            .then(function () {
                btn.disabled = false;
                btn.textContent = originalText;
            });
    });
})();
</script>
<?php endif; ?>
</body>
</html>
