<?php
// 功能：后台文章列表 编辑 发布专用文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。


// 先引入common.php文件，确保handle_article_params()函数可用
if (!defined('COMMON_LOADED')) {
    require_once '../common.php';
}

// 处理文章参数设置的POST请求
handle_article_params();

// 处理更新文章标题的AJAX请求
if (isset($_GET['action']) && $_GET['action'] === 'update_article_title' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    start_admin_session();
    header('Content-Type: application/json; charset=utf-8');
    if (!isset($_POST['article_id']) || !isset($_POST['title'])) {
        echo json_encode(['success' => false, 'message' => '参数错误']);
        exit;
    }
    $article_id = intval($_POST['article_id']);
    $title = trim($_POST['title']);
    global $conn;
    $result = update_article_title($conn, $article_id, $title);
    echo json_encode($result);
    exit;
}

// 检查访问权限
if (!defined('ADMIN_LOADED')) {
    // 允许AJAX POST请求和GET请求获取文章信息
    if ($_SERVER['REQUEST_METHOD'] === 'POST' || (isset($_GET['action']) && $_GET['action'] === 'get_article_info')) {
        require_once dirname(__DIR__) . '/common.php';
        if (!defined('COMMON_LOADED')) {
            define('COMMON_LOADED', true);
        }
        // 初始化数据库连接
        global $conn;
        $conn = get_db_connection();
        define('ADMIN_LOADED', true);
    } else {
        header('HTTP/1.1 403 Forbidden');
        exit('Access Denied');
    }
}

start_admin_session();
check_admin_access();
qk_ensure_posts_extra_columns();

if (!defined('DEFAULT_THUMBNAIL_PATH')) {
    define('DEFAULT_THUMBNAIL_PATH', '/assets/images/moren.jpg');
}

function getProtectedArticles()
{
    $article_json_file = __DIR__ . '/Plugin/Plugin.json';
    $protected_articles = [];

    if (file_exists($article_json_file)) {
        $data = json_decode(file_get_contents($article_json_file), true);
        if (isset($data['protected_articles']) && is_array($data['protected_articles'])) {
            foreach ($data['protected_articles'] as $article) {
                if (isset($article['id']) && isset($article['title'])) {
                    $protected_articles[] = [
                        'id' => intval($article['id']),
                        'title' => trim((string)$article['title'])
                    ];
                }
            }
        }
    }

    return $protected_articles;
}

function getArticleTitleById($article_id)
{
    global $conn;
    if (!$conn) return null;
    $stmt = $conn->prepare("SELECT title FROM posts WHERE id = ? LIMIT 1");
    if (!$stmt) return null;
    $stmt->bind_param('i', $article_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $title = null;
    if ($res && $row = $res->fetch_assoc()) {
        $title = trim((string)($row['title'] ?? ''));
    }
    $stmt->close();
    return $title;
}

function isProtectedArticle($article_id, $article_title, $protected_articles)
{
    $article_id = intval($article_id);
    $article_title = trim((string)$article_title);
    foreach ($protected_articles as $protected) {
        if (intval($protected['id']) === $article_id && trim((string)$protected['title']) === $article_title) {
            return true;
        }
    }
    return false;
}

if (isset($_GET['delete_article']) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    header('Content-Type: application/json');

    $protected_articles = getProtectedArticles();
    $article_id = intval($_GET['delete_article']);
    $article_title = getArticleTitleById($article_id);

    if ($article_title !== null && isProtectedArticle($article_id, $article_title, $protected_articles)) {
        echo json_encode(['success' => false, 'message' => '该文章已被保护']);
    } else if (deleteArticle($article_id)) {
        echo json_encode(['success' => true, 'message' => '文章删除成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '文章删除失败']);
    }
    exit;
}

if ((isset($_GET['batch_delete']) || isset($_POST['batch_delete'])) && (isset($_GET['ajax']) || isset($_POST['ajax'])) && ((isset($_GET['ajax']) && $_GET['ajax'] == '1') || (isset($_POST['ajax']) && $_POST['ajax'] == '1')) && (isset($_GET['article_ids']) || isset($_POST['article_ids']))) {
    header('Content-Type: application/json');

    global $conn;
    if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
        $conn = get_db_connection();
    }

    $protected_articles = getProtectedArticles();
    $article_ids = explode(',', isset($_POST['article_ids']) ? $_POST['article_ids'] : $_GET['article_ids']);
    $id_list = [];
    foreach ($article_ids as $article_id) {
        $article_id = intval($article_id);
        if ($article_id > 0) $id_list[] = $article_id;
    }
    $title_map = [];
    if (!empty($id_list)) {
        $id_sql = implode(',', array_unique($id_list));
        $rs = ($conn && is_object($conn) && !isset($conn->connect_error)) ? $conn->query("SELECT id,title FROM posts WHERE id IN ({$id_sql})") : false;
        if ($rs) {
            while ($row = $rs->fetch_assoc()) {
                $title_map[intval($row['id'])] = trim((string)($row['title'] ?? ''));
            }
            $rs->close();
        }
    }

    $success_count = 0;
    $protected_count = 0;
    $error_count = 0;

    foreach ($article_ids as $article_id) {
        $article_id = intval($article_id);
        $article_title = isset($title_map[$article_id]) ? $title_map[$article_id] : null;
        if ($article_title !== null && isProtectedArticle($article_id, $article_title, $protected_articles)) {
            $protected_count++;
        } else if (deleteArticle($article_id)) {
            $success_count++;
        } else {
            $error_count++;
        }
    }

    $message = '';
    if ($success_count > 0) {
        $message .= "成功删除 {$success_count} 篇文章";
    }
    if ($protected_count > 0) {
        $message .= ($message ? '，' : '') . "有 {$protected_count} 篇被保护无法删除";
    }
    if ($error_count > 0) {
        $message .= ($message ? '，' : '') . "有 {$error_count} 篇删除失败";
    }

    echo json_encode(['success' => $success_count > 0, 'message' => $message]);
    exit;
}

function getArticleTemplates()
{
    if (function_exists('qk_get_template_options_by_page_type')) {
        $templates = qk_get_template_options_by_page_type('post');
        foreach ($templates as $path => $name) {
            if (strpos($path, 'skin/') !== 0 && strpos($name, '（默认）') !== false) {
                $templates[$path] = '0_' . ltrim((string)$name, '0_');
            }
        }
        return $templates;
    }
    return array('post.php' => '0_post.php（默认）');
}

function getArticleTemplateCustomFieldMetaMap($templates)
{
    $metaMap = array();
    foreach ((array)$templates as $templatePath => $templateName) {
        $meta = qk_get_template_custom_field_meta($templatePath);
        if (!empty($meta)) {
            $metaMap[$templatePath] = $meta;
        }
    }
    return $metaMap;
}

$deepseekPluginSwitch = file_exists(__DIR__ . '/Plugin/22_deepseek.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_property']) && isset($_POST['article_id']) && isset($_POST['property'])) {
        check_admin_access();
        $article_id = intval($_POST['article_id']);
        $property = intval($_POST['property']);
        global $conn;
        update_article_property($conn, $article_id, $property);
        exit;
    }

    if ((isset($_POST['update_category_id']) || isset($_POST['update_category'])) && isset($_POST['article_id']) && isset($_POST['category_id'])) {
        check_admin_access();
        $article_id = intval($_POST['article_id']);
        $category_id = intval($_POST['category_id']);
        global $conn;
        update_article_category($conn, $article_id, $category_id);
        exit;
    }

    if (isset($_POST['update_template']) && isset($_POST['article_id']) && isset($_POST['template'])) {
        check_admin_access();
        $article_id = intval($_POST['article_id']);
        $template = trim($_POST['template']);
        if ($template === '') $template = 'post.php';
        global $conn;
        $stmt = $conn->prepare("UPDATE posts SET template = ? WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param('si', $template, $article_id);
            $result = $stmt->execute();
            $stmt->close();
            if ($result) {
                qk_clear_page_cache();
            }
        }
        exit;
    }

    // 处理更新文章标题请求
    if (isset($_POST['update_title']) && isset($_POST['article_id']) && isset($_POST['title'])) {
        check_admin_access();
        $article_id = intval($_POST['article_id']);
        $title = trim($_POST['title']);
        global $conn;
        $result = update_article_title($conn, $article_id, $title);
        header('Content-Type: application/json');
        echo json_encode($result);
        exit;
    }

    // 处理更新文章缩略图请求
    if (isset($_POST['update_thumbnail']) && isset($_POST['article_id']) && isset($_POST['thumbnail'])) {
        $article_id = intval($_POST['article_id']);
        $thumbnail = trim($_POST['thumbnail']);

        // 处理临时缩略图，移动到正式目录
        if (strpos($thumbnail, '/uploads/Temp/') !== false) {
            // 提取文件名
            $parsedUrl = parse_url($thumbnail);
            if (isset($parsedUrl['path'])) {
                $fileName = basename($parsedUrl['path']);
                if (!empty($fileName)) {
                    // 构建临时文件路径和目标文件路径
                    $tempPath = TEMP_UPLOAD_DIR . $fileName;
                    $finalPath = UPLOAD_DIR . $fileName;

                    // 检查临时文件是否存在
                    if (file_exists($tempPath)) {
                        // 移动文件
                        if (rename($tempPath, $finalPath)) {
                            $thumbnail = qk_build_relative_upload_path($fileName);
                        } else {
                            if (copy($tempPath, $finalPath)) {
                                unlink($tempPath);
                                $thumbnail = qk_build_relative_upload_path($fileName);
                            }
                        }
                    }
                }
            }
        }

        global $conn;
        $stmt = $conn->prepare("UPDATE posts SET thumbnail = ? WHERE id = ?");
        $stmt->bind_param('si', $thumbnail, $article_id);
        $result = $stmt->execute();
        $stmt->close();
        if ($result) {
            qk_clear_page_cache();
        }
        header('Content-Type: application/json');
        echo json_encode(['success' => $result, 'message' => $result ? '缩略图更新成功' : '缩略图更新失败', 'data' => ['url' => $thumbnail]]);
        exit;
    }

    // 处理文章图片上传请求
    if (isset($_POST['action']) && $_POST['action'] === 'upload_image' && isset($_FILES['file'])) {
        check_admin_access();
        ensureUploadDirectories();
        $file = $_FILES['file'];
        $fileName = $file['name'];
        $fileTmpName = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if ($fileError !== UPLOAD_ERR_OK) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '文件上传失败']);
            exit;
        }

        if (!in_array($fileExt, $allowedExts)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '不支持的文件类型']);
            exit;
        }

        $maxFileSize = 1 * 1024 * 1024;
        if ($fileSize > $maxFileSize) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '文件大小超过1MB限制']);
            exit;
        }

        $imageType = isset($_POST['image_type']) ? trim((string)$_POST['image_type']) : 'content';
        $autoCropThumbnail = isset($_POST['auto_crop_thumbnail']) && (string)$_POST['auto_crop_thumbnail'] === '1';
        $prefix = $imageType === 'thumbnail' ? 'thumbnail_' : 'article_';
        $newFileName = $prefix . uniqid('', true) . '.' . $fileExt;
        $destination = TEMP_UPLOAD_DIR . $newFileName;

        if (move_uploaded_file($fileTmpName, $destination)) {
            if ($imageType === 'thumbnail' && $autoCropThumbnail) {
                if (!resizeThumbnail($destination, true)) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => '缩略图裁剪失败']);
                    exit;
                }
            }
            $imageUrl = qk_build_relative_upload_path($newFileName, '/uploads/Temp/');
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'message' => '图片上传成功', 'data' => ['url' => $imageUrl]]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '文件保存失败']);
        }
        exit;
    }

    // 处理删除图片请求
    if (isset($_POST['action']) && $_POST['action'] === 'delete_image' && isset($_POST['image_url'])) {
        check_admin_access();
        $imageUrl = $_POST['image_url'];
        $success = false;

        try {
            $parsedUrl = parse_url($imageUrl);
            if (isset($parsedUrl['path'])) {
                $fileName = basename($parsedUrl['path']);

                if (strpos($imageUrl, '/uploads/Temp/') !== false) {
                    $tempPath = TEMP_UPLOAD_DIR . $fileName;
                    if (file_exists($tempPath)) {
                        $success = unlink($tempPath);
                    }
                } else if (strpos($imageUrl, '/uploads/article/') !== false) {
                    $articlePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/article/' . $fileName;
                    if (file_exists($articlePath)) {
                        $success = unlink($articlePath);
                    }
                }

                $tempPath = TEMP_UPLOAD_DIR . $fileName;
                $articlePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/article/' . $fileName;

                if (file_exists($tempPath)) {
                    $success = unlink($tempPath) || $success;
                }
                if (file_exists($articlePath)) {
                    $success = unlink($articlePath) || $success;
                }
            }

            header('Content-Type: application/json');
            echo json_encode(['success' => $success, 'message' => $success ? '图片删除成功' : '图片删除失败']);
        } catch (Exception $e) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '删除图片时发生错误']);
        }
        exit;
    }

    if (isset($_POST['action']) && $_POST['action'] === 'download_remote_images_in_content' && isset($_POST['content'])) {
        check_admin_access();
        ensureUploadDirectories();

        $content = (string)$_POST['content'];
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        $found = 0;
        $replaced = 0;
        $map = [];

        if ($content !== '' && preg_match_all('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content, $m)) {
            $srcs = array_values(array_unique($m[1]));
            foreach ($srcs as $src) {
                $src = trim(html_entity_decode((string)$src, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                if ($src === '') continue;
                if (isset($map[$src])) continue;

                $candidate = $src;
                if (strpos($candidate, '//') === 0) $candidate = 'https:' . $candidate;
                if (strpos($candidate, 'http://') !== 0 && strpos($candidate, 'https://') !== 0) continue;

                $p = @parse_url($candidate);
                $path = isset($p['path']) ? (string)$p['path'] : '';
                $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
                if ($ext === 'jpeg') $ext = 'jpg';
                if (!in_array($ext, $allowedExts, true)) {
                    $map[$src] = '';
                    continue;
                }

                $found++;
                $tempName = 'article_' . uniqid('', true) . '.' . $ext;
                $tempPath = TEMP_UPLOAD_DIR . $tempName;
                $finalPath = UPLOAD_DIR . $tempName;

                $ok = false;
                if (function_exists('curl_init')) {
                    $fp = @fopen($tempPath, 'wb');
                    if ($fp) {
                        $ch = curl_init($candidate);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6);
                        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                        curl_setopt($ch, CURLOPT_FAILONERROR, true);
                        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
                        curl_setopt($ch, CURLOPT_FILE, $fp);
                        $ok = curl_exec($ch);
                        curl_close($ch);
                        fclose($fp);
                    }
                }

                if ($ok === false || !file_exists($tempPath) || filesize($tempPath) <= 0) {
                    if (file_exists($tempPath)) @unlink($tempPath);
                    $map[$src] = '';
                    continue;
                }

                if (!@rename($tempPath, $finalPath)) {
                    if (!@copy($tempPath, $finalPath)) {
                        @unlink($tempPath);
                        $map[$src] = '';
                        continue;
                    }
                    @unlink($tempPath);
                }

                $newUrl = '/uploads/' . $tempName;
                $content = str_replace($src, $newUrl, $content);
                $map[$src] = $newUrl;
                $replaced++;
            }
        }

        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => true, 'data' => ['found' => $found, 'replaced' => $replaced, 'content' => $content, 'map' => $map]], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 处理获取文章信息请求
    if (isset($_GET['action']) && $_GET['action'] === 'get_article_info' && isset($_GET['id'])) {
        $article_id = intval($_GET['id']);
        global $conn;

        // 确保数据库连接已初始化
        if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
            $conn = get_db_connection();
            if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => '数据库连接失败']);
                exit;
            }
        }

        $sql = "SELECT id, thumbnail FROM posts WHERE id = ?";
        $result = execute_query($conn, $sql, array($article_id));
        if ($result !== false) {
            $article = $result->fetch_assoc();
            $result->close();
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'data' => $article]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '获取文章信息失败']);
        }
        exit;
    }
}

if (isset($_GET['delete_article']) || isset($_POST['delete_article'])) {
    $article_id = isset($_GET['delete_article']) ? $_GET['delete_article'] : $_POST['delete_article'];
    $article_id = intval($article_id);
    $protected_articles = getProtectedArticles();
    $article_title = getArticleTitleById($article_id);

    if ($article_title !== null && isProtectedArticle($article_id, $article_title, $protected_articles)) {
        $error = '该文章已被保护';
    } else if (deleteArticle($article_id)) {
        $success = '文章删除成功';
    } else {
        $error = '文章删除失败';
    }
}

// 从GET中获取参数
$action = '';
$articleId = '';

// 支持新的URL格式：edit_id{id} 和 add
foreach ($_GET as $key => $value) {
    if (strpos($key, 'edit_id') === 0) {
        $action = 'edit';
        $articleId = substr($key, 7); // 去掉 'edit_id' 前缀
        break;
    } elseif ($key === 'add') {
        $action = 'add';
        break;
    }
}

// 向后兼容旧的URL格式
if (empty($action)) {
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    $articleId = isset($_GET['id']) ? $_GET['id'] : '';
}

// 设置显示表单的条件
$show_form = $action === 'add' || $action === 'edit' || $action === 'update';

$templates = getArticleTemplates();
$templateCustomFieldMetaMap = getArticleTemplateCustomFieldMetaMap($templates);

$category_id = 0;
$property_id = 0;
$article_list_title_main = '文章管理';
$article_list_title_sub = '全部';

if (!$show_form) {
    foreach ($_GET as $key => $value) {
        if (preg_match('/^p(\d+)_s(\d+)(_cid(\d+))?$/', $key, $matches)) {
            if (isset($matches[4])) $category_id = intval($matches[4]);
        } elseif (preg_match('/^cid(\d+)$/', $key, $matches)) {
            $category_id = intval($matches[1]);
        }
    }

    if (isset($_GET['category_id'])) $category_id = intval($_GET['category_id']);
    if (isset($_GET['property_id'])) $property_id = intval($_GET['property_id']);

    if ($category_id > 0 && isset($conn) && $conn) {
        $category_stmt = $conn->prepare("SELECT name FROM categories WHERE id = ? LIMIT 1");
        if ($category_stmt) {
            $category_stmt->bind_param('i', $category_id);
            $category_stmt->execute();
            $category_result = $category_stmt->get_result();
            $current_category = $category_result ? $category_result->fetch_assoc() : null;
            $category_stmt->close();

            if ($current_category && !empty($current_category['name'])) {
                $article_count = 0;
                $count_stmt = $conn->prepare("SELECT COUNT(*) AS total FROM posts WHERE category_id = ?");
                if ($count_stmt) {
                    $count_stmt->bind_param('i', $category_id);
                    $count_stmt->execute();
                    $count_result = $count_stmt->get_result();
                    $count_row = $count_result ? $count_result->fetch_assoc() : null;
                    if ($count_row && isset($count_row['total'])) $article_count = intval($count_row['total']);
                    $count_stmt->close();
                }
                $article_list_title_sub = $current_category['name'] . '（' . $article_count . '篇）';
            }
        }
    }
}

// 如果是编辑文章，确保articleId存在
if ($action === 'edit' && empty($articleId)) {
    $action = '';
    $show_form = false;
}
?>
<link rel="stylesheet" href="/assets/css/article.css">
<?php if (!$show_form): ?>

    <div class="section-header" style="display: flex; align-items: center; justify-content: space-between;">
        <h2 style="display:flex; align-items:baseline; gap:8px; margin:0;">
            <span><?php echo escape($article_list_title_main); ?></span>
            <span style="font-size:16px; font-weight:500; color:#64748b;"><?php echo escape($article_list_title_sub); ?></span>
        </h2>
        <div style="display: flex; align-items: center; gap: 10px;">
            <button id="batch-operation-btn" class="btn btn-danger action-button section-header-mobile-btn" style="margin-right: 0; display: inline-flex; align-items: center; justify-content: center;">
                <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
                    <rect x="3" y="3" width="7" height="7" rx="1"></rect>
                    <rect x="14" y="3" width="7" height="7" rx="1"></rect>
                    <rect x="14" y="14" width="7" height="7" rx="1"></rect>
                    <rect x="3" y="14" width="7" height="7" rx="1"></rect>
                </svg>
                <span class="section-header-btn-text">批量操作</span>
            </button>
            <button id="show-add-form-btn" class="btn btn-primary action-button section-header-mobile-btn" style="display: inline-flex; align-items: center; justify-content: center;">
                <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" style="margin-right: 6px;">
                    <circle cx="12" cy="12" r="10"></circle>
                    <line x1="12" y1="8" x2="12" y2="16"></line>
                    <line x1="8" y1="12" x2="16" y2="12"></line>
                </svg>
                <span class="section-header-btn-text">发布新文章</span>
            </button>
        </div>
    </div>

    <?php if (isset($success) && !empty($success)): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                if (typeof showToast === 'function') {
                    showToast('<?php echo addslashes($success); ?>', 'success');
                } else {
                    alert('<?php echo addslashes($success); ?>');
                }
            });
        </script>
    <?php elseif (isset($error) && !empty($error)): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                if (typeof showToast === 'function') {
                    showToast('<?php echo addslashes($error); ?>', 'error');
                } else {
                    alert('<?php echo addslashes($error); ?>');
                }
            });
        </script>
    <?php endif; ?>
    <div class="admin-card">
        <div class="table-container">
            <?php
            // 获取分类列表和属性列表
            $categories = getCategories();
            $properties = getArticleProperties();
            ?>

            <script>
                window.articleTemplates = <?php echo json_encode($templates, JSON_UNESCAPED_UNICODE); ?>;
            </script>


            <div class="admin-table-wrapper">
                <div class="admin-table-scroll">
                    <table class="admin-table section-manage">
                        <thead>
                            <tr>
                                <th style="width: 40px;">
                                    <input type="checkbox" id="select-all-articles" class="form-checkbox" style="width: 18px; height: 18px;">
                                </th>
                                <th>ID</th>
                                <th>缩略图</th>
                                <th>标题（双击编辑）</th>
                                <th>
                                    <div style="position: relative; width: 100%; height: 100%; display: flex; align-items: center;">
                                        <span id="category-header" class="category-header-trigger" style="font-weight: 600; cursor: pointer;" onclick="toggleCategoryMenu()">分类栏目</span>
                                        <style>
                                            #category-header.category-header-trigger {
                                                display: inline-flex;
                                                align-items: center;
                                                position: relative;
                                                padding-right: 30px;
                                                gap: 0;
                                            }

                                            #category-header.category-header-trigger::after {
                                                content: '';
                                                position: absolute;
                                                right: 6px;
                                                top: 50%;
                                                transform: translateY(-50%);
                                                width: 16px;
                                                height: 16px;
                                                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23666' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E");
                                                background-repeat: no-repeat;
                                                background-position: center;
                                                background-size: 16px;
                                                pointer-events: none;
                                            }

                                            #category-dropdown-menu {
                                                border: 1px solid #ddd;
                                                border-radius: 0px;
                                                background-color: #fff;
                                                box-shadow: none;
                                                max-height: 360px;
                                                overflow: hidden;
                                                padding: 0;
                                                width: 180px;
                                            }

                                            #category-dropdown-menu .category-dropdown-item {
                                                height: 30px;
                                                line-height: 30px;
                                                padding: 0 10px;
                                                font-size: 14px;
                                                cursor: pointer;
                                                overflow: hidden;
                                                text-overflow: ellipsis;
                                                white-space: nowrap;
                                                color: #333;
                                            }

                                            #category-dropdown-menu .category-dropdown-item:hover {
                                                background-color: var(--primary-color);
                                                color: #fff;
                                            }
                                        </style>
                                        <div id="category-dropdown-menu" style="display: none; position: absolute; top: 100%; left: 0; z-index: 9999;">
                                            <div class="counter-column-menu-content">
                                                <div class="category-dropdown-item" onclick="filterCategory(0)" data-category-id="0">所有分类</div>
                                                <?php foreach ($categories as $cat): ?>
                                                    <div class="category-dropdown-item" onclick="filterCategory(<?php echo $cat['id']; ?>)" data-category-id="<?php echo $cat['id']; ?>"><?php echo escape($cat['name']); ?></div>
                                                <?php endforeach; ?>
                                            </div>
                                            <div class="counter-column-menu-vscroll"><div class="counter-column-menu-vthumb"></div></div>
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div style="position: relative; width: 100%; height: 100%; display: flex; align-items: center;">
                                        <span id="property-header" class="property-header-trigger" style="font-weight: 600; cursor: pointer;" onclick="togglePropertyMenu()">属性</span>
                                        <style>
                                            #property-header.property-header-trigger {
                                                display: inline-flex;
                                                align-items: center;
                                                position: relative;
                                                padding-right: 30px;
                                                gap: 0;
                                            }

                                            #property-header.property-header-trigger::after {
                                                content: '';
                                                position: absolute;
                                                right: 6px;
                                                top: 50%;
                                                transform: translateY(-50%);
                                                width: 16px;
                                                height: 16px;
                                                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23666' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E");
                                                background-repeat: no-repeat;
                                                background-position: center;
                                                background-size: 16px;
                                                pointer-events: none;
                                            }

                                            #property-dropdown-menu {
                                                border: 1px solid #ddd;
                                                border-radius: 0px;
                                                background-color: #fff;
                                                box-shadow: none;
                                                max-height: 360px;
                                                overflow: hidden;
                                                padding: 0;
                                                width: 125px;
                                            }

                                            #property-dropdown-menu .property-dropdown-item {
                                                height: 30px;
                                                line-height: 30px;
                                                padding: 0 10px;
                                                font-size: 14px;
                                                cursor: pointer;
                                                overflow: hidden;
                                                text-overflow: ellipsis;
                                                white-space: nowrap;
                                                color: #333;
                                            }

                                            #property-dropdown-menu .property-dropdown-item:hover {
                                                background-color: var(--primary-color);
                                                color: #fff;
                                            }
                                        </style>
                                        <div id="property-dropdown-menu" style="display: none; position: absolute; top: 100%; left: 0; z-index: 9999;">
                                            <div class="counter-column-menu-content">
                                                <div class="property-dropdown-item" onclick="filterProperty(0)" data-property-id="0">所有属性</div>
                                                <?php foreach ($properties as $prop): ?>
                                                    <div class="property-dropdown-item" onclick="filterProperty(<?php echo $prop['id']; ?>)" data-property-id="<?php echo $prop['id']; ?>"><?php echo escape($prop['name']); ?></div>
                                                <?php endforeach; ?>
                                            </div>
                                            <div class="counter-column-menu-vscroll"><div class="counter-column-menu-vthumb"></div></div>
                                        </div>
                                    </div>
                                </th>
                                <th>评论</th>
                                <th>
                                    <div style="position: relative; width: 100%; height: 100%; display: flex; align-items: center;">
                                        <span id="template-header" class="template-header-trigger" style="font-weight: 600; cursor: pointer;" onclick="toggleTemplateMenu()">绑定模板</span>
                                        <style>
                                            #template-header.template-header-trigger {
                                                display: inline-flex;
                                                align-items: center;
                                                position: relative;
                                                padding-right: 30px;
                                                gap: 0;
                                            }

                                            #template-header.template-header-trigger::after {
                                                content: '';
                                                position: absolute;
                                                right: 6px;
                                                top: 50%;
                                                transform: translateY(-50%);
                                                width: 16px;
                                                height: 16px;
                                                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23666' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E");
                                                background-repeat: no-repeat;
                                                background-position: center;
                                                background-size: 16px;
                                                pointer-events: none;
                                            }

                                            #template-dropdown-menu {
                                                border: 1px solid #ddd;
                                                border-radius: 0px;
                                                background-color: #fff;
                                                box-shadow: none;
                                                max-height: 360px;
                                                overflow: hidden;
                                                padding: 0;
                                                width: 175px;
                                            }

                                            #template-dropdown-menu .template-dropdown-item {
                                                height: 30px;
                                                line-height: 30px;
                                                padding: 0 10px;
                                                font-size: 12px;
                                                cursor: pointer;
                                                overflow: hidden;
                                                text-overflow: ellipsis;
                                                white-space: nowrap;
                                                color: #333;
                                            }

                                            #template-dropdown-menu .template-dropdown-item:hover {
                                                background-color: var(--primary-color);
                                                color: #fff;
                                            }
                                        </style>
                                        <div id="template-dropdown-menu" style="display: none; position: absolute; top: 100%; left: 0; z-index: 9999;">
                                            <div class="counter-column-menu-content">
                                                <div class="template-dropdown-item" onclick="filterTemplate('')" data-template="">所有模板</div>
                                                <?php foreach ($templates as $templatePath => $templateName): ?>
                                                    <div class="template-dropdown-item" onclick="filterTemplate('<?php echo htmlspecialchars(addslashes($templatePath), ENT_QUOTES); ?>')" data-template="<?php echo escape($templatePath); ?>"><?php echo escape($templateName); ?></div>
                                                <?php endforeach; ?>
                                            </div>
                                            <div class="counter-column-menu-vscroll"><div class="counter-column-menu-vthumb"></div></div>
                                        </div>
                                    </div>
                                </th>
                                <th>发布时间</th>
                                <th>更新时间</th>
                                <th class="fixed-action-column">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // 初始渲染首屏文章，减少闪烁
                            if (isset($articles) && !empty($articles)) {
                                $properties = getArticleProperties();
                                foreach ($articles as $article) {
                                    $thumbnail = $article['thumbnail'];
                                    if (empty($thumbnail)) $thumbnail = '/assets/images/moren.jpg';

                                    echo "<tr>";
                                    echo "<td style='width: 40px;'><input type='checkbox' class='article-checkbox' value='{$article['id']}'></td>";
                                    echo "<td>{$article['id']}</td>";
                                    echo "<td><img src='" . escape($thumbnail) . "' alt='" . escape($article['title']) . "' style='width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;' onclick='replaceListThumbnail({$article['id']}, this)'></td>";
                                    echo "<td class='article-title-cell' data-article-id='{$article['id']}'>";
                                    echo "    <span class='article-title-display' ondblclick='editArticleTitle({$article['id']})' data-qk-tip='" . escape($article['title']) . "' data-original-title='" . escape($article['title']) . "'>" . escape($article['title']) . "</span>";
                                    echo "    <input type='text' class='article-title-input' style='display:none; width: 100%; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;' value='" . escape($article['title']) . "' onblur='saveArticleTitle({$article['id']}, this)' onkeydown='if(event.key===\"Enter\"){this.blur();}if(event.key===\"Escape\"){cancelEditArticleTitle({$article['id']});}'>";
                                    echo "</td>";
                                    echo "<td>";
                                    echo "    <form method='post' class='inline-form category-update-form'>";
                                    echo "        <input type='hidden' name='update_category' value='1'>";
                                    echo "        <input type='hidden' name='article_id' value='{$article['id']}'>";
                                    echo "        <select name='category_id' onchange='updateCategory(this)' class='form-control category-select' style='margin-right: 15px; margin-left: -15px; width: auto;'>";
                                    foreach ($categories as $cat) {
                                        $selected = ($article['category_id'] == $cat['id']) ? 'selected' : '';
                                        echo "<option value='{$cat['id']}' $selected>" . escape($cat['name']) . "</option>";
                                    }
                                    echo "        </select>";
                                    echo "    </form>";
                                    echo "</td>";
                                    echo "<td>";
                                    echo "    <form method='post' class='inline-form'>";
                                    echo "        <input type='hidden' name='update_property' value='1'>";
                                    echo "        <input type='hidden' name='article_id' value='{$article['id']}'>";
                                    echo "        <select name='property' onchange='updateProperty(this)' class='form-control status-select' style='margin-right: 15px; margin-left: -15px; width: auto;'>";
                                    foreach ($properties as $prop) {
                                        $selected = ($article['property'] == $prop['id']) ? 'selected' : '';
                                        echo "<option value='{$prop['id']}' $selected>" . escape($prop['name']) . "</option>";
                                    }
                                    echo "        </select>";
                                    echo "    </form>";
                                    echo "</td>";
                                    echo "<td>" . ($article['comment_count'] ?? 0) . "</td>";
                                    echo "<td>";
                                    echo "    <form method='post' class='inline-form'>";
                                    echo "        <input type='hidden' name='update_template' value='1'>";
                                    echo "        <input type='hidden' name='article_id' value='{$article['id']}'>";
                                    echo "        <select name='template' onchange='updateTemplate(this)' class='form-control template-select' style='margin-right: 15px; margin-left: -15px; width: auto;'>";
                                    $currentTemplate = isset($article['template']) && $article['template'] !== '' ? $article['template'] : 'post.php';
                                    foreach ($templates as $templatePath => $templateName) {
                                        $selected = ($currentTemplate == $templatePath) ? 'selected' : '';
                                        echo "<option value='" . escape($templatePath) . "' $selected>" . escape($templateName) . "</option>";
                                    }
                                    echo "        </select>";
                                    echo "    </form>";
                                    echo "</td>";
                                    echo "<td>" . ($article['created_at'] ? date('Y-m-d', strtotime($article['created_at'])) : '-') . "</td>";
                                    echo "<td>" . ($article['updated_at'] ? date('Y-m-d', strtotime($article['updated_at'])) : '-') . "</td>";
                                    echo "<td class='fixed-action-column'>";
                                    $preview_url = '/post_id' . $article['id'] . '.php';
                                    if (!empty($article['custom_url'])) {
                                        $custom_url = trim((string)$article['custom_url']);
                                        if (strpos($custom_url, '/') !== 0) {
                                            $custom_url = '/' . $custom_url;
                                        }
                                        $preview_url = $custom_url;
                                    }
                                    echo "    <a href='" . escape($preview_url) . "' target='_blank' class='btn btn-sm btn-secondary'>预览</a>";
                                    echo "    <button type='button' class='btn btn-sm btn-primary edit-article-btn' data-id='{$article['id']}' data-title='" . escape($article['title']) . "' data-category='{$article['category_id']}' data-keywords='" . escape($article['keywords']) . "' data-property='{$article['property']}' data-thumbnail='" . escape($article['thumbnail']) . "' data-description='" . escape($article['description']) . "' data-points='{$article['points']}' data-mp4url='" . escape($article['mp4url']) . "' data-custom-url='" . escape($article['custom_url']) . "'>编辑</button>";
                                    echo "    <button type='button' onclick='deleteArticleConfirm({$article['id']})' class='btn btn-sm btn-danger'>删除</button>";
                                    echo "</td>";
                                    echo "</tr>";
                                }
                            } else {
                                echo "<tr><td colspan='11' style='text-align: center; padding: 20px;'>暂无文章数据</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
                <!-- 自定义滚动条 -->
                <div class="counter-custom-scrollbar-container">
                    <div class="counter-custom-scrollbar-track">
                        <div class="counter-custom-scrollbar-thumb"></div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <!-- 批量操作模态框 -->
    <div id="batch-operation-modal" class="modal" style="display: none;">
        <div class="modal-backdrop"></div>
        <div class="modal-content" style="max-width: 500px; height: 450px; margin: 100px auto;">
            <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center;  border-bottom: 1px solid #e0e0e0;">
                <h3 class="modal-title">批量操作</h3>
                <button id="close-batch-modal" class="modal-close">&times;</button>
            </div>
            <div class="modal-body" style="padding: 40px; ">
                <div id="selected-count" style="margin-bottom: 20px; padding: 12px; background-color: #f8f9fa; border-radius: 4px; font-size: 14px; color: #666; border-left: 4px solid #007bff;">
                    当前已选择 <span id="count-number" style="font-weight: 600; color: #333;">0</span> 篇文章
                </div>

                <div style="display: flex; flex-direction: column; gap: 15px;">
                    <!-- 批量移动 -->
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <select id="batch-category-select" class="form-control" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; padding-right: 26px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important; background-image: url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E) !important; background-repeat: no-repeat !important; background-position: right 8px center !important; background-size: 14px !important; background-color: white !important;">
                            <option value="0">请选择分类</option>
                            <?php
                            $categories = getCategories();
                            foreach ($categories as $category) {
                                echo '<option value="' . $category['id'] . '">' . escape($category['name']) . '</option>';
                            }
                            ?>
                        </select>
                        <button id="batch-move-btn" class="btn btn-primary" style="width: 130px !important;">批量移动文章</button>
                    </div>

                    <!-- 批量改属性 -->
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <select id="batch-property-select" class="form-control" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; padding-right: 26px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important; background-image: url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E) !important; background-repeat: no-repeat !important; background-position: right 8px center !important; background-size: 14px !important; background-color: white !important;">
                            <option value="0">请选择属性</option>
                            <?php
                            $properties = getArticleProperties();
                            foreach ($properties as $prop_id => $prop) {
                                echo '<option value="' . $prop_id . '">' . escape($prop['name']) . '</option>';
                            }
                            ?>
                        </select>
                        <button id="batch-property-btn" class="btn btn-primary" style="width: 130px !important;">批量修改属性</button>
                    </div>

                    <!-- 批量绑定模板 -->
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <select id="batch-template-select" class="form-control" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; padding-right: 26px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important; background-image: url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E) !important; background-repeat: no-repeat !important; background-position: right 8px center !important; background-size: 14px !important; background-color: white !important;">
                            <option value="0">请选择模板</option>
                            <?php
                            $templates = getArticleTemplates();
                            foreach ($templates as $templatePath => $templateName):
                            ?>
                                <option value="<?php echo $templatePath; ?>"><?php echo $templateName; ?></option>
                            <?php
                            endforeach;
                            ?>
                        </select>
                        <button id="batch-template-btn" class="btn btn-primary" style="width: 130px !important;">批量绑定模板</button>
                    </div>

                    <!-- 批量删除 -->
                    <div style="margin-top: 10px; text-align: right;">
                        <button id="batch-delete-btn" class="btn btn-danger" style="width: 130px !important; display: inline-flex; align-items: center; justify-content: center;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
                                <polyline points="3 6 5 6 21 6"></polyline>
                                <path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"></path>
                                <path d="M19 6l-1 14a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1L5 6"></path>
                                <line x1="10" y1="11" x2="10" y2="17"></line>
                                <line x1="14" y1="11" x2="14" y2="17"></line>
                            </svg>
                            批量删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php else: ?>
    <div class="section-header">
        <h2><?php echo $action === 'edit' ? '编辑文章' : '发布新文章'; ?></h2>
        <div style="display: flex; align-items: center;">

            <?php if ($action === 'edit'): ?>
                <!-- 自定义下拉框 -->
                <div class="article-dropdown-container">
                    <div class="article-custom-dropdown">
                        <div class="article-dropdown-header">
                            <button class="article-select-btn" id="article-select-btn">选择文章</button>
                            <input type="number" class="page-input" id="page-input" min="1" value="1" placeholder="页码">
                        </div>
                        <div class="article-dropdown-options" id="article-dropdown-options" style="display: none;">
                            <div class="article-search-container">
                                <input type="text" class="article-dropdown-search" id="article-dropdown-search" placeholder="搜索文章...">
                                <svg class="article-search-icon" id="article-search-btn" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <circle cx="11" cy="11" r="8"></circle>
                                    <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                                </svg>
                            </div>
                            <div id="article-options-list" class="counter-column-menu-content"></div>
                            <div class="article-dropdown-page-info" id="article-dropdown-page-info">第1页</div>
                            <div class="counter-column-menu-vscroll"><div class="counter-column-menu-vthumb"></div></div>
                            <!-- 选项将通过JavaScript动态添加 -->
                        </div>
                        <select id="article-dropdown" name="article_id"></select>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="admin-card">
        <div id="article-form-container">
            <form id="article-form" name="article-form" method="post" enctype="multipart/form-data" action="/admin/ajaxx.php">
                <?php if ($action === 'edit'): ?>
                    <input type="hidden" name="article_id" value="<?php echo intval($articleId); ?>">
                    <?php
                    $edit_article = null;
                    // 直接查询单篇文章，而不是加载所有文章
                    global $conn;
                    // 查询文章数据，确保包含所有需要的字段
                    $sql = "SELECT p.*, IFNULL(c.name, '未知') as category_name, IFNULL(u.username, '未知') as author, 
                   (SELECT COUNT(*) FROM comments cm WHERE cm.post_id = p.id) as comment_count 
                   FROM posts p LEFT JOIN categories c ON p.category_id = c.id LEFT JOIN users u ON p.user_id = u.id 
                   WHERE p.id = ?";
                    $result = execute_query($conn, $sql, array($articleId));
                    if ($result !== false) {
                        $edit_article = $result->fetch_assoc();
                        $result->close();
                        // 确保浏览量字段存在，并且可以通过views键访问
                        if (isset($edit_article['view_count'])) {
                            $edit_article['views'] = $edit_article['view_count'];
                        }
                    }
                    ?>
                <?php endif; ?>
                <script>
                    (function() {
                        try {
                            if (localStorage.getItem('article_advanced_expanded') === '0') {
                                document.documentElement.classList.add('article-advanced-pref-collapsed');
                            }
                            if (localStorage.getItem('article_extra_expanded') === '0') {
                                document.documentElement.classList.add('article-extra-pref-collapsed');
                            }
                        } catch (e) {}
                    })();
                    window.templateCustomFieldMetaMap = <?php echo json_encode($templateCustomFieldMetaMap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                </script>
                <style>
                    #article-primary-row,
                    #article-secondary-row {
                        align-items: stretch;
                    }

                    #article-title-group,
                    #article-keywords-group,
                    #article-primary-advanced,
                    #article-secondary-advanced {
                        height: 100%;
                    }

                    #article-primary-advanced,
                    #article-secondary-advanced {
                        align-items: stretch;
                    }

                    #article-primary-advanced > div,
                    #article-secondary-advanced > div {
                        display: flex;
                        flex-direction: column;
                        justify-content: flex-end;
                        height: 100%;
                    }

                    #article-title-group,
                    #article-keywords-group {
                        display: flex;
                        flex-direction: column;
                        justify-content: flex-end;
                    }

                    #article-primary-row label,
                    #article-secondary-row label {
                        margin-bottom: 6px;
                        line-height: 1.4;
                    }

                    #article-title-group > label {
                        min-height: 32px;
                    }

                    .article-advanced-pref-collapsed #article-primary-row,
                    .article-advanced-pref-collapsed #article-secondary-row {
                        grid-template-columns: 1fr !important;
                    }

                    .article-advanced-pref-collapsed #article-primary-advanced,
                    .article-advanced-pref-collapsed #article-secondary-advanced {
                        display: none !important;
                    }

                    .article-extra-pref-collapsed #article-extra-row {
                        display: none !important;
                    }
                </style>
                <div class="form-row" id="article-primary-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">
                    <div class="form-group" id="article-title-group" style="margin-bottom: 0; box-sizing: border-box;">
                        <label for="title" title="{qkcms:posts_title}，可在前台模板调用" style="display:flex; align-items:center; justify-content:space-between; gap:10px;">
                            <span>文章标题</span>
                            <span class="article-toolbar-actions">
                                <button type="button" id="toggle-article-extra" class="article-advanced-toggle article-extra-toggle" aria-expanded="true">
                                    <span>附加功能</span>
                                    <svg class="article-extra-toggle-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                                        <path d="M3 6L8 11L13 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                    </svg>
                                </button>
                                <button type="button" id="toggle-article-advanced" class="article-advanced-toggle" aria-expanded="true">
                                    <span>高级选项</span>
                                    <svg class="article-advanced-toggle-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                                        <path d="M6 3L11 8L6 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                    </svg>
                                </button>
                            </span>
                        </label>
                        <input type="text" id="title" name="title" class="form-control" placeholder="请输入文章标题" value="<?php echo isset($edit_article) ? escape($edit_article['title']) : ''; ?>" required style="width: 100%; box-sizing: border-box;">
                    </div>
                    <div class="form-group" id="article-primary-advanced" style="margin-bottom: 0; box-sizing: border-box; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px;">
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="category_id" title="{qkcms:posts_category}，可在前台模板调用">所属分类</label>
                            <select id="category_id" name="category_id" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                                <?php
                                $categories = getCategories();
                                // 判定预选分类ID：编辑模式使用文章分类，发布模式优先使用URL参数，其次才是默认逻辑
                                $pre_selected_category_id = 0;
                                if (isset($edit_article) && isset($edit_article['category_id'])) {
                                    $pre_selected_category_id = $edit_article['category_id'];
                                } elseif (isset($_GET['category_id'])) {
                                    $pre_selected_category_id = intval($_GET['category_id']);
                                } else {
                                    // 检查 cid{id} 格式的参数
                                    foreach ($_GET as $key => $value) {
                                        if (preg_match('/^cid(\d+)$/', $key, $matches)) {
                                            $pre_selected_category_id = intval($matches[1]);
                                            break;
                                        }
                                    }
                                }

                                $current_category_name = '';
                                foreach ($categories as $category):
                                    if ($current_category_name === '' && intval($pre_selected_category_id) === intval($category['id'])) {
                                        $current_category_name = $category['name'];
                                    }
                                ?>
                                    <option value="<?php echo $category['id']; ?>" <?php echo ($pre_selected_category_id == $category['id']) ? 'selected' : ''; ?>> <?php echo escape($category['name']); ?> </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="template">文章模板</label>
                            <select id="template" name="template" class="form-control" style="height: 39px; appearance: none; background-image: url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 16 16%22%3E%3Cpath fill=%22none%22 stroke=%22%237c3aed%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22 stroke-width=%221.5%22 d=%22M3 6l5 5 5-5%22/%3E%3C/svg%3E'); background-repeat: no-repeat; background-position: right 8px center; background-size: 16px; padding-right: 32px; width: 100%; box-sizing: border-box;">
                                <?php
                                $templates = getArticleTemplates();
                                $currentTemplate = isset($edit_article) ? $edit_article['template'] : 'post.php';
                                foreach ($templates as $templatePath => $templateName):
                                    $shortTemplateName = basename($templatePath);
                                ?>
                                    <option value="<?php echo $templatePath; ?>" data-full-label="<?php echo escape($templateName); ?>" data-short-label="<?php echo escape($shortTemplateName); ?>" <?php echo ($currentTemplate == $templatePath) ? 'selected' : ''; ?>><?php echo $templateName; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="article_property" title="{qkcms:posts_property}，可在前台模板调用">文章属性</label>
                            <select id="article_property" name="article_property" class="form-control" style="height: 39px; appearance: none; background-image: url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 16 16%22%3E%3Cpath fill=%22none%22 stroke=%22%237c3aed%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22 stroke-width=%221.5%22 d=%22M3 6l5 5 5-5%22/%3E%3C/svg%3E'); background-repeat: no-repeat; background-position: right 8px center; background-size: 16px; padding-right: 32px; width: 100%; box-sizing: border-box;">
                                <?php
                                $properties = getArticleProperties();
                                $currentProperty = isset($edit_article['property']) ? $edit_article['property'] : 0;
                                foreach ($properties as $prop_id => $prop):
                                ?>
                                    <option value="<?php echo $prop_id; ?>" <?php echo ($currentProperty == $prop_id) ? 'selected' : ''; ?>><?php echo escape($prop['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="top_type">文章置顶</label>
                            <select id="top_type" name="top_type" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                                <option value="0" <?php echo (!isset($edit_article) || !isset($edit_article['top_type']) || intval($edit_article['top_type']) === 0) ? 'selected' : ''; ?>>默认</option>
                                <option value="1" <?php echo (isset($edit_article) && isset($edit_article['top_type']) && intval($edit_article['top_type']) === 1) ? 'selected' : ''; ?>>首页置顶</option>
                                <option value="2" <?php echo (isset($edit_article) && isset($edit_article['top_type']) && in_array(intval($edit_article['top_type']), array(2, 3), true)) ? 'selected' : ''; ?>>列表页置顶</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-row" id="article-secondary-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">

                    <div class="form-group" id="article-keywords-group" style="margin-bottom: 0; box-sizing: border-box;">
                        <label for="keywords" title="{qkcms:posts_keywords}，可在前台模板调用">TAG、关键词 <span class="keywords-hint">(用逗号分隔)</span></label>
                        <input type="text" id="keywords" name="keywords" class="form-control" placeholder="" value="<?php echo isset($edit_article) ? escape($edit_article['keywords']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                    </div>
                    <div class="form-group" id="article-secondary-advanced" style="margin-bottom: 0; box-sizing: border-box; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px;">
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="custom_url" title="{qkcms:posts_custom_url}，可在前台模板调用">自定义URL</label>
                            <input type="text" id="custom_url" name="custom_url" class="form-control" placeholder="仅支持.html或.php后缀，如：abc.html" value="<?php echo isset($edit_article) && isset($edit_article['custom_url']) ? $edit_article['custom_url'] : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="bind_domain">绑定域名</label>
                            <input type="text" id="bind_domain" name="bind_domain" class="form-control" placeholder="如：www.b.com,www.cc.b.com" value="<?php echo isset($edit_article) && isset($edit_article['bind_domain']) ? escape($edit_article['bind_domain']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="views" title="{qkcms:posts_views}，可在前台模板调用">浏览量</label>
                            <input type="number" id="views" name="views" class="form-control" placeholder="浏览量" value="<?php echo isset($edit_article) && isset($edit_article['views']) ? $edit_article['views'] : ''; ?>" min="0" style="height: 39px; width: 100%; box-sizing: border-box;">
                        </div>
                        <div style="margin-bottom: 0; box-sizing: border-box;">
                            <label for="access_password">访问密码</label>
                            <input type="text" id="access_password" name="access_password" class="form-control" placeholder="为空则不限制访问" value="<?php echo isset($edit_article) && isset($edit_article['access_password']) ? escape($edit_article['access_password']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
                <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">
                    <div class="form-group" style="margin-bottom: 0; box-sizing: border-box;">
                        <label for="description" title="{qkcms:posts_description}，可在前台模板调用">文章描述</label>
                        <textarea id="description" name="description" class="form-control" placeholder="请输入文章描述（简洁概括文章内容）" rows="3" style="width: 100%; box-sizing: border-box;"><?php echo isset($edit_article) ? escape($edit_article['description']) : ''; ?></textarea>
                    </div>

                    <div class="form-group" style="margin-bottom: 0; box-sizing: border-box;">
                        <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:6px;flex-wrap:wrap;">
                            <label for="thumbnail" title="{qkcms:posts_thumbnail}，可在前台模板调用" style="margin-bottom:0;">文章缩略图</label>
                            <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                            <label for="auto_crop_thumbnail" style="display:inline-flex;align-items:center;gap:6px;margin:0;font-weight:400;font-size:13px;color:#666;cursor:pointer;user-select:none;">
                                <input type="checkbox" id="auto_crop_thumbnail" name="auto_crop_thumbnail" value="1" checked style="margin:0;">
                                <span>自动裁剪</span>
                            </label>
                            <span style="font-size:12px;color:#94a3b8;">勾选=裁剪160x100，不勾选=保留原图</span>
                            </div>
                        </div>
                        <?php
                        $initial_thumbnail = isset($edit_article) && !empty($edit_article['thumbnail']) ? trim($edit_article['thumbnail']) : '';
                        $thumbnail_source_type = 'upload';
                        $thumbnail_input_display_value = '';
                        if ($initial_thumbnail !== '') {
                            $thumb_is_absolute = preg_match('/^https?:\/\//i', $initial_thumbnail) === 1;
                            $thumb_path = $thumb_is_absolute ? (parse_url($initial_thumbnail, PHP_URL_PATH) ?: '') : $initial_thumbnail;
                            $thumb_host = $thumb_is_absolute ? (parse_url($initial_thumbnail, PHP_URL_HOST) ?: '') : '';
                            $current_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
                            $is_local_upload = strpos($thumb_path, '/uploads/') === 0 || strpos($thumb_path, 'uploads/') === 0;
                            if (($thumb_is_absolute && $thumb_host !== '' && $thumb_host !== $current_host) || !$is_local_upload) {
                                $thumbnail_source_type = 'url';
                                $thumbnail_input_display_value = $initial_thumbnail;
                            } else {
                                $thumbnail_input_display_value = basename($initial_thumbnail);
                            }
                        }
                        ?>
                        <div class="thumbnail-upload-container">
                            <input type="file" id="thumbnail" name="thumbnail" class="form-control-file" style="display: none;" accept="image/*">
                            <div id="thumbnail-preview" class="thumbnail-preview" style="pointer-events: auto; height: auto; margin-bottom: 10px; display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 4px; justify-content: space-between;">
                                <div style="display: flex; align-items: center; gap: 10px; flex: 1;">
                                    <button type="button" id="thumbnail-upload-btn" class="thumbnail-upload-btn">选择文件</button>
                                    <div class="thumbnail-input-wrap">
                                        <input type="text" id="thumbnail-url-input" class="form-control" value="<?php echo escape($thumbnail_input_display_value); ?>" placeholder="支持上传图片，也可直接输入云端图片URL" style="width: 100%; min-width: 220px; flex: 1;">
                                        <?php if ($initial_thumbnail !== ''): ?>
                                            <input type="hidden" name="existing_thumbnail" value="<?php echo escape($initial_thumbnail); ?>">
                                            <input type="hidden" name="thumbnail_source_type" value="<?php echo $thumbnail_source_type; ?>">
                                        <?php endif; ?>
                                        <button type="button" id="thumbnail-delete-btn" class="thumbnail-delete-btn delete-thumbnail<?php echo $initial_thumbnail !== '' ? ' has-value' : ''; ?>">删除</button>
                                    </div>
                                </div>
                                <div id="thumbnail-preview-box-wrap">
                                    <?php if ($initial_thumbnail !== ''): ?>
                                        <div class="thumbnail-preview-box" data-thumbnail="<?php echo escape($initial_thumbnail); ?>" style="width: 80px; height: 40px; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                            <img src="<?php echo escape($initial_thumbnail); ?>" alt="缩略图预览" style="max-width: 100%; max-height: 100%; object-fit: cover;">
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <input type="hidden" id="article_points" name="article_points" value="<?php echo isset($edit_article) && isset($edit_article['points']) ? $edit_article['points'] : '0'; ?>">

                <div class="form-row article-form-row" id="article-extra-row" style="display: flex; gap: 10px; margin-bottom: 15px; box-sizing: border-box; align-items: flex-end;">
                    <div style="display: flex; gap: 10px; flex: 1;">
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; width: 140px;">
                            <label for="function_type">附加功能</label>
                            <select id="function_type" name="function_type" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                                <option value="tool" <?php echo (!isset($edit_article) || (isset($edit_article['function_type']) && $edit_article['function_type'] == 'tool')) ? 'selected' : ''; ?>>工具类（付费后开放操作权限）</option>
                                <option value="resource" <?php echo (isset($edit_article) && isset($edit_article['function_type']) && $edit_article['function_type'] == 'resource') ? 'selected' : ''; ?>>资源类（付费后开放下载权限）</option>
                                <option value="custom" <?php echo (isset($edit_article) && isset($edit_article['function_type']) && $edit_article['function_type'] == 'custom') ? 'selected' : ''; ?>>自定义字段（用于前端扩展）</option>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; flex: 1;" id="tool-url-container">
                            <label for="tool_url" title="{qkcms:posts_tool_url}，可在前台模板调用">前台工具URL</label>
                            <input type="text" id="tool_url" name="tool_url" class="form-control" placeholder="请输入前台工具URL" value="<?php echo isset($edit_article) && isset($edit_article['tool_url']) ? escape($edit_article['tool_url']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; flex: 1; display: none;" id="custom-field-1-container">
                            <label for="custom_field_1" data-default-label="自定义字段1">自定义字段1</label>
                            <input type="text" id="custom_field_1" name="custom_field_1" class="form-control" placeholder="custom_field_1" data-default-placeholder="custom_field_1" value="<?php echo isset($edit_article) && isset($edit_article['custom_field_1']) ? escape($edit_article['custom_field_1']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px; flex: 1;" id="right-container">
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; flex: 1;" id="redirect-url-container">
                            <label for="redirect_url" title="{qkcms:posts_redirect_url}，可在前台模板调用">付费后跳转URL</label>
                            <input type="text" id="redirect_url" name="redirect_url" class="form-control" placeholder="可输入自定义资源路径" value="<?php echo isset($edit_article) && isset($edit_article['redirect_url']) ? escape($edit_article['redirect_url']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; flex: 1; display: none;" id="custom-field-2-container">
                            <label for="custom_field_2" data-default-label="自定义字段2">自定义字段2</label>
                            <input type="text" id="custom_field_2" name="custom_field_2" class="form-control" placeholder="custom_field_2" data-default-placeholder="custom_field_2" value="<?php echo isset($edit_article) && isset($edit_article['custom_field_2']) ? escape($edit_article['custom_field_2']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; flex: 1; display: none;" id="custom-field-3-container">
                            <label for="custom_field_3" data-default-label="自定义字段3">自定义字段3</label>
                            <input type="text" id="custom_field_3" name="custom_field_3" class="form-control" placeholder="custom_field_3" data-default-placeholder="custom_field_3" value="<?php echo isset($edit_article) && isset($edit_article['custom_field_3']) ? escape($edit_article['custom_field_3']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; width: 100px;" id="status-switch-container">
                            <label for="status_switch" title="{qkcms:posts_status_switch}，可在前台模板调用">开关</label>
                            <select id="status_switch" name="status_switch" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                                <option value="0" <?php echo (isset($edit_article) && isset($edit_article['status_switch']) && $edit_article['status_switch'] == 0) ? 'selected' : ''; ?>>关闭</option>
                                <option value="1" <?php echo (!isset($edit_article) || (isset($edit_article['status_switch']) && $edit_article['status_switch'] == 1)) ? 'selected' : ''; ?>>开启</option>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom: 0; box-sizing: border-box; width: 120px;" id="price-container">
                            <label for="price" title="{qkcms:posts_price}，可在前台模板调用">售价</label>
                            <input type="number" id="price" name="price" class="form-control" placeholder="请输入售价" value="<?php echo isset($edit_article) && isset($edit_article['price']) ? intval($edit_article['price']) : '0'; ?>" min="0" step="1" style="height: 39px; width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <style>
                    /* 手机端自适应样式 */
                    @media (max-width: 768px) {
                        .form-row {
                            grid-template-columns: 1fr !important;
                        }

                        .form-row .form-group {
                            grid-template-columns: 1fr !important;
                        }

                        .article-form-row {
                            flex-direction: column !important;
                            align-items: stretch !important;
                        }

                        .article-form-row>div {
                            flex-direction: column !important;
                            gap: 10px !important;
                        }

                        .article-form-row>div>div {
                            width: 100% !important;
                        }

                        #thumbnail-preview {
                            flex-direction: column !important;
                            align-items: stretch !important;
                        }

                        #thumbnail-preview>div {
                            width: 100% !important;
                        }

                        /* 列表右上角按钮手机端样式 */
                        .section-header-mobile-btn {
                            width: 38px !important;
                            height: 38px !important;
                            min-width: 38px !important;
                            padding: 0 !important;
                        }
                        .section-header-mobile-btn .section-header-btn-text {
                            display: none !important;
                        }
                        .section-header-mobile-btn .section-header-btn-icon {
                            margin-right: 0 !important;
                        }
                    }
                </style>

                <div class="form-group">
                    <label for="content" style="display:flex;align-items:center;justify-content:space-between;">
                        <span>文章内容</span>
                        <span style="display:flex;align-items:center;gap:6px;font-weight:400;font-size:13px;">
                            <input type="checkbox" id="download_remote_images" name="download_remote_images" value="1">
                            将云端图片下载到本地
                        </span>
                    </label>
                    <div class="editor-wrapper" style="border-radius:5px;">
                        <div id="quill-editor" style="height: 400px;"></div>
                    </div>
                    <textarea id="content" name="content" style="display: none;"><?php echo isset($edit_article) ? escape($edit_article['content']) : ''; ?></textarea>
                </div>

                <?php if (!isset($edit_article)): ?>
                    <script>
                        // 保存下拉框值到本地存储（仅在发布模式下）
                        document.addEventListener('DOMContentLoaded', function() {
                            const selectElements = [{
                                    id: 'category_id',
                                    key: 'article_category_id'
                                },
                                {
                                    id: 'article_property',
                                    key: 'qk_cms_article_property'
                                },
                                {
                                    id: 'template',
                                    key: 'article_template'
                                }
                            ];

                            // 为所有下拉框添加change事件监听器
                            selectElements.forEach(({
                                id,
                                key
                            }) => {
                                const element = document.getElementById(id);
                                if (element) {
                                    // 检查URL中是否有category_id，如果有，则不应用localStorage中的分类设置
                                     const urlParams = new URLSearchParams(window.location.search);
                                     let urlCategoryId = urlParams.get('category_id');

                                     // 检查 cid{id} 格式的参数
                                     if (!urlCategoryId) {
                                         for (const key of urlParams.keys()) {
                                             const match = key.match(/^cid(\d+)$/);
                                             if (match) {
                                                 urlCategoryId = match[1];
                                                 break;
                                             }
                                         }
                                     }

                                    // 从本地存储读取并设置值
                                    const savedValue = localStorage.getItem(key);
                                    if (savedValue !== null) {
                                        // 如果是分类下拉框且URL中有分类ID，则跳过localStorage设置
                                        if (id === 'category_id' && urlCategoryId) {
                                            // 保持PHP渲染的选择
                                        } else {
                                            element.value = savedValue;
                                        }
                                    }

                                    // 添加change事件监听器
                                    element.addEventListener('change', function() {
                                        localStorage.setItem(key, this.value);
                                    });
                                }
                            });
                        });
                    </script>
                <?php endif; ?>

                <style>
                    .article-toolbar-actions {
                        display: inline-flex;
                        align-items: center;
                        gap: 8px;
                        flex-wrap: wrap;
                        justify-content: flex-end;
                    }

                    .article-advanced-toggle {
                        display: inline-flex;
                        align-items: center;
                        gap: 6px;
                        height: 32px;
                        padding: 0 12px;
                        border: 1px solid #d8dee9;
                        border-radius: 6px;
                        background: #fff;
                        color: var(--primary-color);
                        font-size: 12px;
                        line-height: 1;
                        cursor: pointer;
                        flex-shrink: 0;
                    }

                    .article-advanced-toggle:hover {
                        background: rgba(124, 58, 237, 0.06);
                    }

                    .article-advanced-toggle-icon {
                        color: #64748b;
                        transition: none;
                    }

                    .article-extra-toggle-icon {
                        color: #64748b;
                        transition: none;
                    }

                    .article-advanced-pref-collapsed #toggle-article-advanced .article-advanced-toggle-icon {
                        transform: rotate(180deg);
                    }

                    .article-advanced-toggle.is-collapsed .article-advanced-toggle-icon {
                        transform: rotate(180deg);
                    }

                    .article-extra-pref-collapsed #toggle-article-extra .article-extra-toggle-icon {
                        transform: none;
                    }

                    .article-extra-toggle.is-collapsed .article-extra-toggle-icon {
                        transform: none;
                    }

                    #toggle-article-extra .article-extra-toggle-icon {
                        transform: rotate(180deg);
                    }

                    #article-form-container .thumbnail-upload-btn {
                        background: #fff;
                        color: #475569;
                        border: 1px solid #d8dee9;
                        box-shadow: none;
                        height: 38px;
                        line-height: 38px;
                        padding: 0 14px;
                    }

                    #article-form-container .thumbnail-upload-btn:hover {
                        background: #f5f6f8ff;
                        color: #334155;
                        border-color: #cbd5e1;
                        transform: none;
                        box-shadow: none;
                    }

                    #article-form-container .thumbnail-input-wrap {
                        position: relative;
                        flex: 1;
                        min-width: 220px;
                    }

                    #article-form-container .thumbnail-input-wrap .form-control {
                        height: 38px;
                        padding-right: 42px;
                    }

                    #article-form-container .thumbnail-delete-btn {
                        position: absolute;
                        top: 50%;
                        right: 10px;
                        transform: translateY(-50%);
                        width: 24px;
                        height: 24px;
                        border: none;
                        background: #dbdbdb;
                        border-radius: 50%;
                        cursor: pointer;
                        color: transparent;
                        font-size: 0;
                        padding: 0;
                        display: inline-flex;
                        align-items: center;
                        justify-content: center;
                        opacity: 0;
                        visibility: hidden;
                        pointer-events: none;
                        transition: all .2s ease;
                        z-index: 2;
                    }

                    #article-form-container .thumbnail-delete-btn::before,
                    #article-form-container .thumbnail-delete-btn::after {
                        content: '';
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        width: 10px;
                        height: 2px;
                        background: #fff;
                        transform: translate(-50%, -50%) rotate(45deg);
                    }

                    #article-form-container .thumbnail-delete-btn::after {
                        transform: translate(-50%, -50%) rotate(-45deg);
                    }

                    #article-form-container .thumbnail-input-wrap:hover .thumbnail-delete-btn.has-value,
                    #article-form-container .thumbnail-input-wrap:focus-within .thumbnail-delete-btn.has-value {
                        opacity: 1;
                        visibility: visible;
                        pointer-events: auto;
                    }

                    #article-form-container .thumbnail-delete-btn:hover {
                        background: #ff5252;
                        transform: translateY(-50%) rotate(90deg);
                    }
                </style>

                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        const templateSelect = document.getElementById('template');
                        if (!templateSelect) return;

                        function restoreTemplateOptionLabels() {
                            Array.from(templateSelect.options).forEach(function(option) {
                                const fullLabel = option.getAttribute('data-full-label');
                                if (fullLabel) option.text = fullLabel;
                            });
                        }

                        function applyTemplateShortLabel() {
                            restoreTemplateOptionLabels();
                            const selectedOption = templateSelect.options[templateSelect.selectedIndex];
                            if (!selectedOption) return;
                            const shortLabel = selectedOption.getAttribute('data-short-label');
                            if (shortLabel) selectedOption.text = shortLabel;
                        }

                        templateSelect.addEventListener('mousedown', restoreTemplateOptionLabels);
                        templateSelect.addEventListener('focus', restoreTemplateOptionLabels);
                        templateSelect.addEventListener('blur', applyTemplateShortLabel);
                        templateSelect.addEventListener('change', function() {
                            setTimeout(applyTemplateShortLabel, 0);
                        });

                        applyTemplateShortLabel();
                    });
                </script>

                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        const root = document.documentElement;
                        const extraToggleButton = document.getElementById('toggle-article-extra');
                        const extraRow = document.getElementById('article-extra-row');
                        const extraStorageKey = 'article_extra_expanded';
                        if (extraToggleButton && extraRow) {
                            function setExtraVisible(expanded) {
                                root.classList.toggle('article-extra-pref-collapsed', !expanded);
                                extraToggleButton.classList.toggle('is-collapsed', !expanded);
                                extraToggleButton.setAttribute('aria-expanded', expanded ? 'true' : 'false');
                                try {
                                    localStorage.setItem(extraStorageKey, expanded ? '1' : '0');
                                } catch (e) {}
                            }

                            extraToggleButton.addEventListener('click', function() {
                                const expanded = extraToggleButton.getAttribute('aria-expanded') === 'true';
                                setExtraVisible(!expanded);
                            });

                            let initialExtraExpanded = true;
                            try {
                                const savedExtraState = localStorage.getItem(extraStorageKey);
                                if (savedExtraState === '0') initialExtraExpanded = false;
                            } catch (e) {}
                            setExtraVisible(initialExtraExpanded);
                        }

                        const toggleButton = document.getElementById('toggle-article-advanced');
                        const primaryRow = document.getElementById('article-primary-row');
                        const secondaryRow = document.getElementById('article-secondary-row');
                        const primaryAdvanced = document.getElementById('article-primary-advanced');
                        const secondaryAdvanced = document.getElementById('article-secondary-advanced');
                        const storageKey = 'article_advanced_expanded';
                        if (!toggleButton || !primaryRow || !secondaryRow || !primaryAdvanced || !secondaryAdvanced) return;

                        function setAdvancedVisible(expanded) {
                            root.classList.toggle('article-advanced-pref-collapsed', !expanded);
                            toggleButton.classList.toggle('is-collapsed', !expanded);
                            toggleButton.setAttribute('aria-expanded', expanded ? 'true' : 'false');
                            try {
                                localStorage.setItem(storageKey, expanded ? '1' : '0');
                            } catch (e) {}
                        }

                        toggleButton.addEventListener('click', function() {
                            const expanded = toggleButton.getAttribute('aria-expanded') === 'true';
                            setAdvancedVisible(!expanded);
                        });

                        let initialExpanded = true;
                        try {
                            const savedState = localStorage.getItem(storageKey);
                            if (savedState === '0') initialExpanded = false;
                        } catch (e) {}
                        setAdvancedVisible(initialExpanded);
                    });
                </script>

                <div id="imagePropertiesModal" class="modal">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width: 420px; max-width: 420px;">
                        <div class="modal-header">
                            <h3 class="modal-title">图片属性</h3>
                            <button type="button" id="closeModal" class="modal-close">&times;</button>
                        </div>
                        <div class="modal-body" style="padding-bottom:0px">
                            <div class="form-group">
                                <label for="imageUrl">图片URL:</label>
                                <input type="text" id="imageUrl" placeholder="输入图片地址" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="imageWidth">宽度 (px):</label>
                                <input type="number" id="imageWidth" min="50" max="2000" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="imageHeight">高度 (px):</label>
                                <input type="number" id="imageHeight" min="50" max="2000" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="imageAlt">ALT 文本:</label>
                                <input type="text" id="imageAlt" placeholder="输入图片描述" class="form-control">
                            </div>
                        </div>
                        <div class="modal-footer" style="display: flex; align-items: center; justify-content: space-between; padding-top:0px">
                            <label style="margin: 0; display: flex; align-items: center;">
                                <input type="checkbox" id="preserveAspectRatio" checked style="margin-right: 8px; margin-left:13px">
                                保持宽高比
                            </label>
                            <div class="modal-actions" style="margin: 0; margin-right:8px">
                                <button type="button" id="cancelChanges" class="btn btn-secondary">取消</button>
                                <button type="button" id="applyChanges" class="btn btn-primary">应用</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="videoInsertModal" class="modal">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width: 450px; max-width: 450px; height: 460px; max-height: 460px;">
                        <div class="modal-header">
                            <h3 class="modal-title">视频属性</h3>
                            <button type="button" class="modal-close" onclick="closeVideoInsertModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label for="video-url">MP4视频地址</label>
                                <input type="text" id="video-url" placeholder="请输入MP4视频地址" class="form-control">
                            </div>
                            <div class="form-group">

                                <div style="display:flex;align-items:center;gap:20px;margin-bottom:10px;">
                                    <div style="display:flex;align-items:center;gap:5px;">
                                        <input type="checkbox" id="autoplay" style="margin:0;">
                                        <label for="autoplay" style="margin:0;">自动播放</label>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:5px;">
                                        <input type="checkbox" id="videoPreserveAspectRatio" checked style="margin:0;">
                                        <label for="videoPreserveAspectRatio" style="margin:0;">尺寸自适应</label>
                                    </div>
                                </div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px;">
                                    <div>
                                        <label for="video-width">视频宽度</label>
                                        <input type="number" id="video-width" value="790" min="100" max="1200" class="form-control">
                                    </div>
                                    <div>
                                        <label for="video-height">视频高度</label>
                                        <input type="number" id="video-height" value="550" min="100" max="800" class="form-control">
                                    </div>
                                </div>
                                <div class="buy-content-section" style="margin-bottom:10px;">
                                    <div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;    margin-top: 20px;">
                                        <input type="checkbox" id="video-buy-content" style="margin:0;vertical-align:middle;">
                                        <label for="video-buy-content" style="margin:0;vertical-align:middle;">付费可见 请在下面输入框里面设置积分</label>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:5px;">
                                        <input type="number" id="video-buy-points" value="10" min="1" max="9999" class="form-control">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-actions" style="padding:16px 32px;border-top:1px solid #e0e0e0;display:flex;justify-content:flex-end;gap:10px;">
                            <button type="button" class="btn btn-secondary" onclick="closeVideoInsertModal()">取消</button>
                            <button type="button" class="btn btn-danger" onclick="deleteVideo()">删除</button>
                            <button type="button" class="btn btn-primary" onclick="confirmVideoInsert()">确认</button>
                        </div>
                    </div>
                </div>
                <div id="aiPluginModal" class="modal">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width: 810px; max-width:810px; height: 520px; max-height: 520px;">
                        <div class="modal-header">
                            <h3 class="modal-title">AI智能写作助手</h3>
                            <button type="button" class="modal-close" onclick="closeAiPluginModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div id="ai-plugin-content"></div>
                        </div>
                    </div>
                </div>

                <div id="imageUrlInsertModal" class="modal" style="display:none;">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width: 520px; max-width:520px;">
                        <div class="modal-header">
                            <h3 class="modal-title">插入图片URL</h3>
                            <button type="button" class="modal-close" onclick="closeImageUrlInsertModal()">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label for="cloudImageUrlInput">图片URL</label>
                                <input type="text" id="cloudImageUrlInput" class="form-control" placeholder="https://... 或 /uploads/...">
                            </div>
                        </div>
                        <div class="modal-actions">
                            <button type="button" class="btn btn-secondary" id="cloudImageUrlCancelBtn">取消</button>
                            <button type="button" class="btn btn-primary" id="cloudImageUrlConfirmBtn">确定</button>
                        </div>
                    </div>
                </div>

                <link href="../assets/quill/quill.snow.css" rel="stylesheet">
                <script src="../assets/js/toast.js"></script>
                <script src="../assets/quill/quill.min.js"></script>


                <script>
                    window.categoriesData = <?php
                                            $categories = getCategories();
                                            $categoriesArray = [];
                                            foreach ($categories as $category) {
                                                $categoriesArray[] = ['id' => $category['id'], 'name' => escape($category['name'])];
                                            }
                                            echo json_encode($categoriesArray);
                                            ?>;
                    window.isEditMode = <?php echo isset($edit_article) ? 'true' : 'false'; ?>;
                    window.deepseekPluginSwitch = <?php echo $deepseekPluginSwitch ? 'true' : 'false'; ?>;
                    window.aiImagePluginExists = <?php echo file_exists(__DIR__ . '/Plugin/46_aiimage.php') ? 'true' : 'false'; ?>;
                </script>

                <input type="hidden" name="form_mode" id="form_mode" value="<?php echo $action === 'edit' ? 'edit' : 'add'; ?>">
                <input type="hidden" name="article_id" id="article_id" value="<?php echo $articleId; ?>">
                <button type="submit" name="<?php echo $action === 'edit' ? 'edit_article' : 'publish_article'; ?>" id="submit-button" class="btn btn-primary" style="width: 100px;"><?php echo $action === 'edit' ? '更新文章' : '发布文章'; ?></button>
                <button type="button" id="preview-button" class="btn btn-primary ml-2" style="width: 70px;">预览</button>
                <button type="button" id="cancel-button" class="btn btn-secondary ml-2" style="min-width: 70px; width: auto; white-space: nowrap;"><?php echo $current_category_name !== '' ? '返回' . escape($current_category_name) : '返回'; ?></button>
                <button type="button" id="continue-publish-button" class="btn btn-primary ml-2" style="display: none; min-width: 70px; width: auto; white-space: nowrap;">继续发布</button>
            </form>
        </div>

    <?php endif; ?>
    <script src="../assets/js/article.js"></script>
