<?php

require_once __DIR__ . '/common.php';
require_once __DIR__ . '/../includes/debug-log.php';

admin_require_login();

$pdo       = db();
$adminUser = admin_current_user();
$siteTitle = get_setting('site.title', '六柱博客');

$articleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$debugReqId = 'ae_' . date('Ymd_His') . '_' . substr(md5(uniqid('', true)), 0, 8);

$errors = [];
$saved = false;


$data = [
    'title'           => '',
    'summary'         => '',
    'content_html'    => '',
    'category_id'     => 0,
    'status'          => 'draft',
    'is_recommended'  => 0,
    'is_home_candidate' => 0,
    'published_at'    => '',
    'tags_text'       => '',
];


$categories = [];
try {
    $stmt = $pdo->query("
        SELECT id, name FROM categories ORDER BY sort_order DESC, id ASC
    ");
    $categories = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $categories = [];
}


$allTags = [];
try {
    $stmt = $pdo->query("
        SELECT id, name
        FROM tags
        ORDER BY name COLLATE NOCASE ASC, id ASC
    ");
    $allTags = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $allTags = [];
}


if ($articleId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT * FROM articles WHERE id = :id LIMIT 1
        ");
        $stmt->execute([':id' => $articleId]);
        $row = $stmt->fetch();
        if ($row) {
            $data['title'] = (string)$row['title'];
            $data['summary'] = (string)$row['summary'];
            $data['content_html'] = (string)$row['content_html'];
            $data['category_id'] = (int)$row['category_id'];
            $data['status'] = (string)$row['status'];
            $data['is_recommended'] = (int)$row['is_recommended'];
            $data['is_home_candidate'] = (int)$row['is_home_candidate'];
            $data['published_at'] = $row['published_at'] ? date('Y-m-d H:i:s', (int)$row['published_at']) : '';

            
            $tagsText = '';
            try {
                $stmtTags = $pdo->prepare("
                    SELECT t.name
                    FROM article_tag at
                    INNER JOIN tags t ON t.id = at.tag_id
                    WHERE at.article_id = :aid
                    ORDER BY t.id ASC
                ");
                $stmtTags->execute([':aid' => $articleId]);
                $names = [];
                while ($tr = $stmtTags->fetch()) {
                    $names[] = $tr['name'];
                }
                $tagsText = implode(', ', $names);
            } catch (Throwable $e) {
                $tagsText = '';
            }
            $data['tags_text'] = $tagsText;
        } else {
            $articleId = 0; 
        }
    } catch (Throwable $e) {
        $errors[] = '操作失败：' . $e->getMessage();
        $articleId = 0;
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfOk = admin_csrf_check($_POST['csrf_token'] ?? null);
    if (!$csrfOk) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    }

    $data['title'] = trim((string)($_POST['title'] ?? ''));
    $data['summary'] = trim((string)($_POST['summary'] ?? ''));
    $data['content_html'] = trim((string)($_POST['content_html'] ?? ''));
    $data['content_html'] = str_replace(["\xEF\xBB\xBF", "\u{5728}\u{8FD9}\u{91CC}\u{8F93}\u{5165}\u{5185}\u{5BB9}...", "\u{5728}\u{8FD9}\u{91CC}\u{8F93}\u{5165}\u{5185}\u{5BB9}\u{2026}"], '', $data['content_html']);
    if ($data['content_html'] !== '') {
        $data['content_html'] = normalize_hidden_blocks_before_save($data['content_html']);
        $data['content_html'] = normalize_html_newlines($data['content_html']);
    }

    $data['category_id'] = (int)($_POST['category_id'] ?? 0);
    $data['status'] = (string)($_POST['status'] ?? 'draft');
    $data['is_recommended'] = isset($_POST['is_recommended']) ? 1 : 0;
    $data['is_home_candidate'] = isset($_POST['is_home_candidate']) ? 1 : 0;
    $data['published_at'] = trim((string)($_POST['published_at'] ?? ''));
    $data['tags_text'] = trim((string)($_POST['tags_text'] ?? ''));

    blog_debug_log('article_edit_image.log', [
        'event' => 'save_start',
        'req' => $debugReqId,
        'admin_id' => isset($adminUser['id']) ? (int)$adminUser['id'] : 0,
        'article_id' => $articleId,
        'csrf_ok' => $csrfOk ? 1 : 0,
        'content_html_len' => strlen((string)$data['content_html']),
        'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
    ]);

    if ($data['title'] === '') {
        $errors[] = '标题不能为空。';
    }

    if ($data['content_html'] === '') {
        $errors[] = '正文内容不能为空。';
    }

    $allowedStatus = ['draft', 'pending', 'published', 'rejected'];
    if (!in_array($data['status'], $allowedStatus, true)) {
        $data['status'] = 'draft';
    }

    
    $publishedTs = null;
    if ($data['status'] === 'published') {
        if ($data['published_at'] !== '') {
            $ts = strtotime($data['published_at']);
            if ($ts === false) {
                $errors[] = '发布时间格式不正确，建议使用“YYYY-MM-DD HH:MM:SS”。';
            } else {
                $publishedTs = $ts;
            }
        } else {
            $publishedTs = time();
        }
    }

    if (!$errors) {
        try {
            $now = time();

            if ($articleId > 0) {
                
                $stmt = $pdo->prepare("
                    UPDATE articles
                    SET title = :title,
                        summary = :summary,
                        content_html = :content_html,
                        category_id = :category_id,
                        status = :status,
                        is_recommended = :is_recommended,
                        is_home_candidate = :is_home_candidate,
                        updated_at = :updated_at,
                        published_at = :published_at
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':title'            => $data['title'],
                    ':summary'          => $data['summary'],
                    ':content_html'     => $data['content_html'],
                    ':category_id'      => $data['category_id'] ?: null,
                    ':status'           => $data['status'],
                    ':is_recommended'   => $data['is_recommended'],
                    ':is_home_candidate'=> $data['is_home_candidate'],
                    ':updated_at'       => $now,
                    ':published_at'     => $publishedTs,
                    ':id'               => $articleId,
                ]);
                admin_log('article_update', '修改文章 ID=' . $articleId . ' 标题=' . $data['title']);
            } else {
                
                $stmt = $pdo->prepare("
                    INSERT INTO articles
                        (title, slug, content_html, summary, category_id,
                         author_id, status, is_recommended, is_home_candidate,
                         view_count, like_count, comment_count,
                         created_at, updated_at, published_at)
                    VALUES
                        (:title, NULL, :content_html, :summary, :category_id,
                         :author_id, :status, :is_recommended, :is_home_candidate,
                         0, 0, 0,
                         :created_at, :updated_at, :published_at)
                ");
                $stmt->execute([
                    ':title'            => $data['title'],
                    ':content_html'     => $data['content_html'],
                    ':summary'          => $data['summary'],
                    ':category_id'      => $data['category_id'] ?: null,
                    ':author_id'        => (int)$adminUser['id'],
                    ':status'           => $data['status'],
                    ':is_recommended'   => $data['is_recommended'],
                    ':is_home_candidate'=> $data['is_home_candidate'],
                    ':created_at'       => $now,
                    ':updated_at'       => $now,
                    ':published_at'     => $publishedTs,
                ]);
                $articleId = (int)$pdo->lastInsertId();
                admin_log('article_create', '新建文章 ID=' . $articleId . ' 标题=' . $data['title']);
            }

            
            save_article_tags($pdo, $articleId, $data['tags_text']);

            $saved = true;

            blog_debug_log('article_edit_image.log', [
                'event' => 'save_ok',
                'req' => $debugReqId,
                'admin_id' => isset($adminUser['id']) ? (int)$adminUser['id'] : 0,
                'article_id' => $articleId,
                'status' => $data['status'],
                'content_html_len' => strlen((string)$data['content_html']),
                'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
            ]);
        } catch (Throwable $e) {
            blog_debug_log('article_edit_image.log', [
                'event' => 'save_failed',
                'req' => $debugReqId,
                'admin_id' => isset($adminUser['id']) ? (int)$adminUser['id'] : 0,
                'article_id' => $articleId,
                'error' => blog_debug_preview($e->getMessage()),
            ]);
            $errors[] = '操作失败：' . $e->getMessage();
        }
    }
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?php echo $articleId > 0 ? '编辑文章' : '新建文章'; ?> - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #020617;
            color: #e5e7eb;
        }

        a {
            color: #60a5fa;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        .topbar {
            background: #0f172a;
            border-bottom: 1px solid #1f2937;
            padding:18px 16px 6px;
            display: flex;
            align-items:flex-start;
            justify-content: space-between;
         margin:0;  margin-top:-12px; }

        .topbar-title {
            font-size: 16px;
            font-weight: 600;
        }
        .topbar-user {
            font-size: 13px;
            color: #9ca3af;
        }
        .topbar-nav a {
            margin-left: 10px;
            font-size: 13px;
        }

        .page {
            max-width: 900px;
            margin: 0 auto;
            padding: 16px;
        }

        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
            margin-bottom: 12px;
        }

        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .form-row {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
        }

        .form-row label {
            width: 70px;
            font-size: 13px;
        }

        .form-row input,
        .form-row select,
        .form-row textarea {
            flex: 1;
            padding: 4px 6px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 13px;
        }
        .form-row .tox-tinymce,
        .form-row .tox {
            flex: 1;
            width: 100% !important;
            max-width: 100%;
        }

        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 13px;
            padding: 5px 10px;
            cursor: pointer;
            margin-top: 8px;
        }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }

        .success {
            background: #14532d;
            border: 1px solid #22c55e;
            color: #bbf7d0;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }

        .small-text {
            font-size: 12px;
            color: #9ca3af;
            margin-top: 4px;
        }
        .hidden-comment-block {
            border: 1px dashed #f59e0b;
            background: #fffbeb;
            color: #111827;
            padding: 8px 10px;
            border-radius: 6px;
            margin: 8px 0;
        }
        .hidden-comment-block p {
            margin: 0 0 6px;
        }
        .hidden-comment-block p:last-child {
            margin-bottom: 0;
        }
        .hidden-comment-block strong {
        color: #b45309;
    }
    .hidden-comment-block .hidden-label {
        font-weight: 600;
    }
    .hidden-comment-block .hidden-label[contenteditable="false"] {
        user-select: none;
    }
    .hidden-comment-block .hidden-content[data-empty="1"]::before {
        content: attr(data-placeholder);
        color: #9ca3af;
    }
    [data-hidden-marker^="comment-only"] {
        display: none !important;
    }
        .attach-input {
            display: none;
        }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="topbar">
        <div class="topbar-title"><?php echo $articleId > 0 ? '编辑文章' : '新建文章'; ?></div>
        <div class="topbar-user">
            管理员：<?php echo h($adminUser['nickname'] ?? $adminUser['email'] ?? ''); ?>
            <span class="topbar-nav">
                <a href="index.php">仪表</a>
                <a href="articles.php">文章</a>
                <a href="categories.php">分类</a>
                <a href="tags.php">&#26631;&#31614;</a>
                <a href="comments.php">评论</a>
                <a href="links.php">友链</a>
                <a href="media.php">文件</a>
                <a href="users.php">会员</a>
                <a href="sensitive_words.php">敏感</a>
                <a href="stats.php">流量</a>
                <a href="security.php">防护</a>
                <a href="logs.php">日志</a>
                <a href="settings.php">设置</a>

                <a href="backup_sqlite.php">&#25968;&#25454;</a>
                <a href="../index.php">前台</a>
                <a href="../logout.php">退</a>
            </span>
        </div>
    </div>

    <div class="page">
        <?php if ($errors): ?>
            <div class="errors">
                <?php foreach ($errors as $err): ?>
                    <div><?php echo h($err); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php if ($saved && !$errors): ?>
            <div class="success">文章已保存</div>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
            <div class="card">
                <div class="card-title">基本信息</div>
                <div class="form-row">
                    <label for="title">标题</label>
                    <input type="text" id="title" name="title" value="<?php echo h($data['title']); ?>" required>
                </div>
                <div class="form-row">
                    <label for="category_id">分类</label>
                    <select id="category_id" name="category_id">
                        <option value="0">未分类</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo (int)$cat['id']; ?>" <?php echo $data['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo h($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-row">
                    <label for="summary">摘要</label>
                    <textarea id="summary" name="summary" rows="2"><?php echo h($data['summary']); ?></textarea>
                </div>
                <div class="form-row">
                    <label for="content_html">正文（富文本）</label>
                    <textarea id="content_html" name="content_html" rows="14"><?php echo h($data['content_html']); ?></textarea>
                    <input type="file" id="image-input" class="attach-input" accept="image/*">
                    <input type="file" id="attach-input" class="attach-input" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.md,.zip,.rar,.7z">
                    <input type="file" id="video-input" class="attach-input" accept="video/mp4,video/webm,video/ogg">
                </div>
                <div class="small-text">
                    已接入富文本编辑器（TinyMCE），支持图片、附件与视频上传<br>
                    附件支持格式：pdf/doc/docx/xls/xlsx/ppt/pptx/txt/md/zip/rar/7z，大小不超过 10MB<br>
                    视频支持格式：mp4/webm/ogg，大小不超过 50MB<br>
                    如需设置“隐藏内容 · 评论可见”的区域，可在正文中使用以下标记包裹需要隐藏的内容<br>
                    <code>&lt;!--hidden:comment-only:start--&gt;这里是隐藏内容块&lt;!--hidden:comment-only:end--&gt;</code><br>
                    同一篇文章中可以多次使用上述标记；访客在本篇文章下至少有一条“已通过审核”的评论后，才能看到这些隐藏内容。                </div>
            </div>

            <div class="card">
                <div class="card-title">发布选项</div>
                <div class="form-row">
                    <label for="status">状态</label>
                    <select id="status" name="status">
                        <option value="draft" <?php echo $data['status'] === 'draft' ? 'selected' : ''; ?>>草稿</option>
                        <option value="pending" <?php echo $data['status'] === 'pending' ? 'selected' : ''; ?>>待审</option>
                        <option value="published" <?php echo $data["status"] === "published" ? "selected" : ""; ?>>已发布</option>
                        <option value="rejected" <?php echo $data["status"] === "rejected" ? "selected" : ""; ?>>已驳回</option>
                    </select>
                </div>
                <div class="form-row">
                    <label for="published_at">发布时间</label>
                    <input type="text" id="published_at" name="published_at" value="<?php echo h($data["published_at"]); ?>" placeholder="留空则使用当前时间">
                </div>
                <div class="form-row">
                    <label>推荐文章</label>
                    <input type="checkbox" name="is_recommended" <?php echo $data["is_recommended"] ? "checked" : ""; ?>> 是                </div>
                <div class="form-row">
                    <label>首页候选（随机首页）</label>
                    <input type="checkbox" name="is_home_candidate" <?php echo $data["is_home_candidate"] ? "checked" : ""; ?>> 是                </div>
            </div>

            <div class="card">
                <div class="card-title">标签</div>
                <div class="form-row">
                    <label for="tags_text">标签列表</label>
                    <input type="text" id="tags_text" name="tags_text" value="<?php echo h($data["tags_text"]); ?>" placeholder="多个标签用逗号或空格分隔">
                </div>
                <div class="small-text">
                    标签将用于前台的标签聚合与内部链接，例如：PHP, SQLite, 随笔。                </div>
                <?php if ($allTags): ?>
                    <div class="small-text" style="margin-top:6px;">
                        点击下面的已有标签可快速选择（可多选），也可以在上面的输入框里输入新标签。                    </div>
                    <div class="form-row" style="flex-direction:column; align-items:flex-start;">
                        <div class="tag-selector">
                            <?php
                            $currentTags = trim((string)$data['tags_text']);
                            foreach ($allTags as $t):
                                $name = (string)$t['name'];
                                $isSelected = false;
                                if ($currentTags !== '') {
                                    $pattern = '/(^|[，\\s])' . preg_quote($name, '/') . '([，\\s]|$)/u';
                                    $isSelected = (bool)preg_match($pattern, $currentTags);
                                }
                            ?>
                                <button type="button"
                                        class="tag-choice<?php echo $isSelected ? ' is-selected' : ''; ?>"
                                        data-tag="<?php echo h($name); ?>"
                                        style="border-radius:999px;border:1px solid #374151;background:#020617;color:#e5e7eb;font-size:12px;padding:2px 8px;cursor:pointer;margin:2px 4px 2px 0;">
                                    <?php echo h($name); ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <button type="submit" class="btn">保存文章</button>
        </form>
    </div>
<script src="/assets/tinymce/tinymce.min.js"></script>
<script>

(function () {
    if (!window.tinymce) return;
    var textarea = document.getElementById('content_html');
    if (!textarea) return;

    var csrfToken = <?php echo json_encode(csrf_token()); ?>;
    var imageInput = document.getElementById('image-input');
    var attachInput = document.getElementById('attach-input');
    var videoInput = document.getElementById('video-input');
    var editorInstance = null;

    var hiddenLabel = '隐藏内容（评论可见）';
    var hiddenInputPlaceholder = '在这里输入内容...';

    function markersToBlocks(html) {
        return String(html || '').replace(/<!--hidden:comment-only:start-->([\s\S]*?)<!--hidden:comment-only:end-->/g, function (_, inner) {
            var body = (inner || '').trim();
            if (!body) {
                body = '<p class="hidden-content" data-hidden-content="1" data-placeholder="' + hiddenInputPlaceholder + '" data-empty="1"><br></p>';
            }
            return '<blockquote data-hidden-block="comment-only" class="hidden-comment-block"><p class="hidden-label" contenteditable="false"><strong>' + hiddenLabel + '</strong></p>' + body + '</blockquote>';
        });
    }

    function getEditor() {
        return editorInstance || tinymce.get('content_html') || tinymce.activeEditor || null;
    }

    function cleanHiddenBlocks(editor) {
        if (!editor) return;
        var body = editor.getBody();
        if (!body) return;
        var nodes = body.querySelectorAll('.hidden-content[data-hidden-content="1"]');
        if (!nodes.length) return;
        nodes.forEach(function (el) {
            var rawText = el.textContent || '';
            var cleaned = rawText
                .replace(/\uFEFF/g, '')
                .replace(/\u200B|\u2063|\u2064/g, '')
                .replace(/在这里输入内容\.{3}/g, '')
                .replace(/在这里输入内容…/g, '')
                .trim();
            if (cleaned !== rawText) {
                el.textContent = cleaned;
            }
            var hasNonBr = !!el.querySelector('*:not(br)');
            var finalText = (el.textContent || '').replace(/\s+/g, '').trim();
            if (!hasNonBr && finalText === '') {
                el.setAttribute('data-empty', '1');
                if ((el.innerHTML || '').trim() === '') {
                    el.innerHTML = '<br>';
                }
            } else {
                el.removeAttribute('data-empty');
            }
        });
    }

    if (textarea.value) {
        textarea.value = markersToBlocks(textarea.value);
    }

    tinymce.init({
        selector: '#content_html',
        height: 460,
        menubar: false,
        base_url: '/assets/tinymce',
        suffix: '.min',
        language: 'zh_CN',
        language_url: '/assets/tinymce/i18n/zh_CN.js',
        placeholder: '在这里输入内容...',
        plugins: 'link image lists table code media',
        toolbar: 'undo redo | blocks | bold italic underline | bullist numlist | link table | uploadImage hiddenComment attachFile uploadVideo | code',
        convert_urls: false,
        relative_urls: false,
        images_file_types: 'jpg,jpeg,png,gif,webp',
        content_style: 'body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,system-ui,sans-serif;font-size:14px;line-height:1.7;color:#e5e7eb;background:#0f172a;}img{max-width:100%;height:auto;display:block;margin:6px 0;} .hidden-comment-block{border:1px dashed #f59e0b;background:#fffbeb;color:#111827;padding:8px 10px;border-radius:6px;margin:8px 0;} .hidden-comment-block p{margin:0 0 6px;} .hidden-comment-block p:last-child{margin-bottom:0;} .hidden-comment-block strong{color:#b45309;} .hidden-comment-block .hidden-content{min-height:32px;cursor:text;} .hidden-comment-block .hidden-content[data-empty="1"]:before{content:attr(data-placeholder);color:#9ca3af;}',
        setup: function (editor) {
            editorInstance = editor;
            editor.ui.registry.addButton('uploadImage', {
                text: '图片',
                onAction: function () {
                    if (imageInput) imageInput.click();
                }
            });
            editor.ui.registry.addButton('hiddenComment', {
                text: '隐藏内容',
                onAction: function () {
                    var html = '<blockquote data-hidden-block="comment-only" class="hidden-comment-block"><p class="hidden-label" contenteditable="false"><strong>' + hiddenLabel + '</strong></p><p class="hidden-content" data-hidden-content="1" data-placeholder="' + hiddenInputPlaceholder + '" data-empty="1"><br></p></blockquote><p></p>';
                    editor.insertContent(html);
                }
            });
            editor.ui.registry.addButton('attachFile', {
                text: '附件',
                onAction: function () {
                    if (attachInput) attachInput.click();
                }
            });
            editor.ui.registry.addButton('uploadVideo', {
                text: '视频',
                onAction: function () {
                    if (videoInput) videoInput.click();
                }
            });
            editor.on('change keyup SetContent', function () {
                cleanHiddenBlocks(editor);
            });
        },
        images_upload_handler: function (blobInfo) {
            return new Promise(function (resolve, reject) {
                var fd = new FormData();
                fd.append('file', blobInfo.blob(), blobInfo.filename());
                fd.append('csrf_token', csrfToken);
                fetch('../upload_image.php', {
                    method: 'POST',
                    headers: { 'X-CSRF-Token': csrfToken },
                    credentials: 'same-origin',
                    body: fd
                }).then(function (res) {
                    return res.json();
                }).then(function (json) {
                    if (json && json.errno === 0 && json.data && json.data.url) {
                        resolve(json.data.url);
                    } else {
                        reject((json && json.message) ? json.message : '图片上传失败');
                    }
                }).catch(function () {
                    reject('图片上传失败，请稍后重试');
                });
            });
        }
    });

    function escapeHtml(str) {
        return String(str || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    if (attachInput) {
        attachInput.addEventListener('change', function () {
            var file = attachInput.files && attachInput.files[0];
            if (!file) return;
            var fd = new FormData();
            fd.append('file', file);
            fd.append('csrf_token', csrfToken);
            fetch('../upload_file.php', {
                method: 'POST',
                headers: { 'X-CSRF-Token': csrfToken },
                credentials: 'same-origin',
                body: fd
            }).then(function (res) {
                return res.json();
            }).then(function (json) {
                if (json && json.errno === 0 && json.data && json.data.url) {
                    var name = json.data.name || file.name;
                    var url = json.data.url;
                    var ed = getEditor();
                    if (ed) {
                        var node = ed.selection ? ed.selection.getNode() : null;
                        var p = node && (node.nodeName && node.nodeName.toLowerCase() === 'p' ? node : (ed.dom && ed.dom.getParent ? ed.dom.getParent(node, 'p') : null));
                        var html = p
                            ? '<br><a href="' + encodeURI(url) + '" target="_blank" rel="nofollow noopener">' + escapeHtml(name) + '</a>'
                            : '<p><a href="' + encodeURI(url) + '" target="_blank" rel="nofollow noopener">' + escapeHtml(name) + '</a></p>';
                        ed.insertContent(html);
                    }
                } else {
                    alert((json && json.message) ? json.message : '附件上传失败');
                }
            }).catch(function () {
                alert('附件上传失败，请稍后重试');
            }).finally(function () {
                attachInput.value = '';
            });
        });
    }

    if (imageInput) {
        imageInput.addEventListener('change', function () {
            var file = imageInput.files && imageInput.files[0];
            if (!file) return;
            var fd = new FormData();
            fd.append('file', file);
            fd.append('csrf_token', csrfToken);
            fetch('../upload_image.php', {
                method: 'POST',
                headers: { 'X-CSRF-Token': csrfToken },
                credentials: 'same-origin',
                body: fd
            }).then(function (res) {
                return res.json();
            }).then(function (json) {
                if (json && json.errno === 0 && json.data && json.data.url) {
                    var url = json.data.url;
                    var ed = getEditor();
                    if (ed) ed.insertContent('<p><img src="' + encodeURI(url) + '" alt=""></p>');
                } else {
                    alert((json && json.message) ? json.message : '图片上传失败');
                }
            }).catch(function () {
                alert('图片上传失败，请稍后重试');
            }).finally(function () {
                imageInput.value = '';
            });
        });
    }

    if (videoInput) {
        videoInput.addEventListener('change', function () {
            var file = videoInput.files && videoInput.files[0];
            if (!file) return;
            var fd = new FormData();
            fd.append('file', file);
            fd.append('csrf_token', csrfToken);
            fetch('../upload_video.php', {
                method: 'POST',
                headers: { 'X-CSRF-Token': csrfToken },
                credentials: 'same-origin',
                body: fd
            }).then(function (res) {
                return res.json();
            }).then(function (json) {
                if (json && json.errno === 0 && json.data && json.data.url) {
                    var url = json.data.url;
                    var ed = getEditor();
                    if (ed) ed.insertContent('<p><video controls playsinline style="max-width:100%;" src="' + encodeURI(url) + '"></video></p>');
                } else {
                    alert((json && json.message) ? json.message : '视频上传失败');
                }
            }).catch(function () {
                alert('视频上传失败，请稍后重试');
            }).finally(function () {
                videoInput.value = '';
            });
        });
    }

    var form = textarea.closest('form');
    if (form) {
        form.addEventListener('submit', function () {
            if (window.tinymce) {
                tinymce.triggerSave();
                var ed = getEditor();
                if (ed) {
                    cleanHiddenBlocks(ed);
                    textarea.value = ed.getContent();
                }
            }
        });
    }
})();


(function () {
    var input = document.getElementById('tags_text');
    if (!input) return;
    var buttons = document.querySelectorAll('.tag-choice');
    if (!buttons.length) return;

    function normalizeList(str) {
        if (!str) return [];
        var parts = str.split(/[,，\s]+/);
        var list = [];
        for (var i = 0; i < parts.length; i++) {
            var p = (parts[i] || '').trim();
            if (!p) continue;
            if (list.indexOf(p) === -1) {
                list.push(p);
            }
        }
        return list;
    }

    function syncButtonsFromInput() {
        var names = normalizeList(input.value);
        buttons.forEach(function (btn) {
            var name = btn.getAttribute('data-tag') || '';
            if (!name) return;
            if (names.indexOf(name) !== -1) {
                btn.classList.add('is-selected');
            } else {
                btn.classList.remove('is-selected');
            }
        });
    }

    buttons.forEach(function (btn) {
        btn.addEventListener('click', function () {
            var name = btn.getAttribute('data-tag') || '';
            if (!name) return;
            var names = normalizeList(input.value);
            var idx = names.indexOf(name);
            if (idx === -1) {
                names.push(name);
                btn.classList.add('is-selected');
            } else {
                names.splice(idx, 1);
                btn.classList.remove('is-selected');
            }
            input.value = names.join(', ');
        });
    });

    input.addEventListener('blur', syncButtonsFromInput);
    syncButtonsFromInput();
})();
</script>
</body>
</html>
