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


track_visit(null);

$pdo = db();

$siteTitle              = get_setting('site.title', '六柱博客');
$siteSubtitle           = get_setting('site.subtitle', '六柱个人博客');
$siteDescription        = get_setting('site.description', '六柱个人博客');
$siteFooterBrand        = get_setting('site.footer_brand', '六柱php轻型博客源码');
$siteFooterOfficialUrl  = get_setting('site.footer_official_url', 'https://www.6zjz.com');
$siteFooterOfficialText = get_setting('site.footer_official_text', 'www.6zjz.com');

$enablePosting = get_setting('post.enable_member_posting', '1') === '1';
$autoApproveAfter = (int)get_setting('post.auto_approve_after', '0');

$currentUser = current_user();
$uid = $currentUser ? (int)$currentUser['id'] : 0;
$savedArticleId = 0;
$savedStatus = '';
$debugReqId = 'mp_' . date('Ymd_His') . '_' . substr(md5(uniqid('', true)), 0, 8);

if (!$uid) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发布文章 - 需要登录</title></head><body style="margin:0;padding:0;">';
    echo '<p>请先 <a href="login.php">登录</a> 后再投稿</p>';
    echo '</body></html>';
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT status, is_post_banned FROM users WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $uid]);
    $uRow = $stmt->fetch();
    if (!$uRow || $uRow['status'] !== 'active') {
        echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发布文章 - 账号异常</title></head><body style="margin:0;padding:0;">';
        echo '<p>你的账号已被禁用或状态异常，无法投稿</p>';
        echo '</body></html>';
        exit;
    }
    if (!empty($uRow['is_post_banned'])) {
        echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发布文章 - 投稿被禁</title></head><body style="margin:0;padding:0;">';
        echo '<p>你的账号已被禁止投稿，如有疑问请联系站长</p>';
        echo '</body></html>';
        exit;
    }
} catch (Throwable $e) {
    
}

if (!$enablePosting) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发布文章 - 未开启</title></head><body style="margin:0;padding:0;">';
    echo '<p>当前系统尚未开启发布文章功能</p>';
    echo '</body></html>';
    exit;
}

$errors = [];
$saved  = false;
$uploadedImagesRaw = '';

$data = [
    'title'        => '',
    'summary'      => '',
    'content_html' => '',
    'content_text' => '',
    'category_id'  => 0,
    'tags_text'    => '',
];

require_once __DIR__ . '/includes/sidebar-data.php';
extract(load_common_sidebar_data($pdo), EXTR_OVERWRITE);


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['member_post_started_at'] = time();
}

$categoriesForSelect = [];
foreach ($categories as $row) {
    $categoriesForSelect[] = [
        'id'   => $row['id'],
        'name' => $row['name'],
    ];
}
$defaultCategoryId = $categoriesForSelect[0]['id'] ?? 0;
if ($data['category_id'] === 0 && $defaultCategoryId) {
    $data['category_id'] = $defaultCategoryId;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rateOk = rate_limit_cooldown('member_post', 30);
    if (!$rateOk) {
        $errors[] = '请求过于频繁，请稍后再试。';
    }

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

    $data['title']        = trim((string)($_POST['title'] ?? ''));
    $data['summary']      = trim((string)($_POST['summary'] ?? ''));
    $rawContentHtml       = trim((string)($_POST['content_html'] ?? ''));
    
    $rawContentHtml       = str_replace(["\xEF\xBB\xBF", "在这里输入内容...", "在这里输入内容…"], '', $rawContentHtml);
    $data['content_html'] = $rawContentHtml;
    $rawContentHtmlHasImg = preg_match('/<img\\b/i', (string)$rawContentHtml) ? 1 : 0;
    $data['category_id']  = (int)($_POST['category_id'] ?? 0);
    $data['tags_text']    = trim((string)($_POST['tags_text'] ?? ''));
    $rawContentText       = trim((string)($_POST['content_text'] ?? ''));
    $rawContentText       = str_replace(["\xEF\xBB\xBF", "在这里输入内容...", "在这里输入内容…"], '', $rawContentText);
    $data['content_text'] = $rawContentText;
    $rawUploadedImages    = trim((string)($_POST['uploaded_images'] ?? ''));
    $uploadedImagesRaw    = $rawUploadedImages;
    $uploadedImages       = [];
    $uploadedImagesSource = 'none';

    blog_debug_log('member_post_image.log', [
        'event' => 'submit_start',
        'req' => $debugReqId,
        'uid' => $uid,
        'rate_ok' => $rateOk ? 1 : 0,
        'csrf_ok' => $csrfOk ? 1 : 0,
        'title_len' => strlen((string)$data['title']),
        'content_html_len' => strlen((string)$rawContentHtml),
        'content_html_has_img' => $rawContentHtmlHasImg,
        'content_html_preview' => blog_debug_preview((string)$rawContentHtml),
        'content_text_len' => strlen((string)$rawContentText),
        'uploaded_images_raw_len' => strlen((string)$rawUploadedImages),
        'uploaded_images_raw_preview' => blog_debug_preview((string)$rawUploadedImages),
        'session_started_at' => isset($_SESSION['member_post_started_at']) ? (int)$_SESSION['member_post_started_at'] : null,
    ]);
    if ($rawUploadedImages !== '') {
        $decoded = json_decode($rawUploadedImages, true);
        if (is_array($decoded)) {
            foreach ($decoded as $item) {
                if (!is_string($item)) {
                    continue;
                }
                $url = trim($item);
                if ($url === '') {
                    continue;
                }
                $lower = strtolower($url);
                if (strpos($lower, 'http://') === 0 || strpos($lower, 'https://') === 0 || strpos($lower, '//') === 0 || strpos($url, '/') === 0 || strpos($url, 'uploads/') === 0) {
                    $uploadedImages[] = $url;
                }
            }
        } else {
            $parts = preg_split('/\\s*,\\s*/', $rawUploadedImages, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($parts as $url) {
                $url = trim((string)$url);
                if ($url === '') {
                    continue;
                }
                $lower = strtolower($url);
                if (strpos($lower, 'http://') === 0 || strpos($lower, 'https://') === 0 || strpos($lower, '//') === 0 || strpos($url, '/') === 0 || strpos($url, 'uploads/') === 0) {
                    $uploadedImages[] = $url;
                }
            }
        }
        if ($uploadedImages) {
            $uploadedImages = array_values(array_unique($uploadedImages));
            $uploadedImagesSource = 'post';
            blog_debug_log('member_post_image.log', [
                'event' => 'uploaded_images_from_post',
                'req' => $debugReqId,
                'uid' => $uid,
                'count' => count($uploadedImages),
                'list' => $uploadedImages,
            ]);
        }
    }

    
    
    $imagesFromHtml = [];
    if ($rawContentHtmlHasImg) {
        $imgSrcPattern = "~<img\\b[^>]*\\bsrc\\s*=\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s>]+))~i";
        if (preg_match_all($imgSrcPattern, (string)$rawContentHtml, $m)) {
            $cands = array_merge($m[1] ?: [], $m[2] ?: [], $m[3] ?: []);
            $prefix = '/uploads/editor_images/img' . $uid . '_';
            foreach ($cands as $u) {
                if (!is_string($u)) {
                    continue;
                }
                $u = html_entity_decode($u, ENT_QUOTES, 'UTF-8');
                $u = str_replace(["\xEF\xBB\xBF", "\xE2\x80\x8B", "\xE2\x81\xA3", "\xE2\x81\xA4"], '', $u);
                $u = str_replace('\\/', '/', $u);
                $u = str_replace('\\', '/', $u);
                $u = trim($u);

                
                $pos = strpos($u, '/uploads/editor_images/');
                if ($pos !== false) {
                    $u = substr($u, $pos);
                } elseif (strpos($u, 'uploads/editor_images/') === 0) {
                    $u = '/' . $u;
                }

                if ($u !== '' && strpos($u, $prefix) === 0) {
                    $imagesFromHtml[] = $u;
                }
            }
            if ($imagesFromHtml) {
                $imagesFromHtml = array_values(array_unique($imagesFromHtml));
                $uploadedImages = array_values(array_unique(array_merge($uploadedImages, $imagesFromHtml)));
                if ($uploadedImagesSource === 'none') {
                    $uploadedImagesSource = 'html';
                } elseif ($uploadedImagesSource === 'post') {
                    $uploadedImagesSource = 'post+html';
                } else {
                    $uploadedImagesSource = $uploadedImagesSource . '+html';
                }
                blog_debug_log('member_post_image.log', [
                    'event' => 'uploaded_images_from_html',
                    'req' => $debugReqId,
                    'uid' => $uid,
                    'count' => count($imagesFromHtml),
                    'list' => $imagesFromHtml,
                ]);
            }
        }
    }

    
    
    if (APP_DEBUG) {
        
        if (!$uploadedImages && !empty($_SESSION['recent_uploads']) && is_array($_SESSION['recent_uploads'])) {
            $now = time();
            $recent = [];
            foreach ($_SESSION['recent_uploads'] as $item) {
                if (!is_array($item)) {
                    continue;
                }
                if (($item['type'] ?? '') !== 'image') {
                    continue;
                }
                if ((int)($item['uid'] ?? 0) !== $uid) {
                    continue;
                }
                $t = (int)($item['time'] ?? 0);
                if ($t <= 0 || ($now - $t) > 1800) {
                    continue;
                }
                $url = trim((string)($item['url'] ?? ''));
                if ($url === '') {
                    continue;
                }
                $recent[] = $url;
            }
            if ($recent) {
                $uploadedImages = array_values(array_unique($recent));
                $uploadedImagesSource = 'session';
                blog_debug_log('member_post_image.log', [
                    'event' => 'uploaded_images_from_session',
                    'req' => $debugReqId,
                    'uid' => $uid,
                    'count' => count($uploadedImages),
                    'list' => $uploadedImages,
                ]);
            }
        }
        
        if (!$uploadedImages) {
            try {
                $since = time() - 1800;
                if (!empty($_SESSION['member_post_started_at'])) {
                    $startedAt = (int)$_SESSION['member_post_started_at'];
                    
                    $since = max($startedAt, time() - 86400);
                }
                $stmt = $pdo->prepare("
                    SELECT path
                    FROM media_files
                    WHERE type = 'image'
                      AND uploader_id = :uid
                      AND created_at >= :since
                    ORDER BY id ASC
                    LIMIT 20
                ");
                $stmt->execute([
                    ':uid' => $uid,
                    ':since' => $since,
                ]);
                $rows = $stmt->fetchAll() ?: [];
                foreach ($rows as $row) {
                    $url = trim((string)($row['path'] ?? ''));
                    if ($url !== '') {
                        $uploadedImages[] = $url;
                    }
                }
                if ($uploadedImages) {
                    $uploadedImages = array_values(array_unique($uploadedImages));
                    if (count($uploadedImages) > 1) {
                        $uploadedImages = [end($uploadedImages)];
                    }
                    $uploadedImagesSource = 'media_files';
                    blog_debug_log('member_post_image.log', [
                        'event' => 'uploaded_images_from_media_files',
                        'req' => $debugReqId,
                        'uid' => $uid,
                        'since' => $since,
                        'count' => count($uploadedImages),
                        'list' => $uploadedImages,
                    ]);
                }
            } catch (Throwable $e) {
                
            }
        }
        
        if (!$uploadedImages) {
            $since = time() - 1800;
            if (!empty($_SESSION['member_post_started_at'])) {
                $startedAt = (int)$_SESSION['member_post_started_at'];
                $since = max($startedAt, time() - 86400);
            }
            $imgDir = BASE_PATH . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'editor_images';
            if (is_dir($imgDir)) {
                $files = @scandir($imgDir) ?: [];
                $matched = [];
                $prefix = 'img' . $uid . '_';
                foreach ($files as $file) {
                    if ($file === '.' || $file === '..') {
                        continue;
                    }
                    if (strpos($file, $prefix) !== 0) {
                        continue;
                    }
                    $full = $imgDir . DIRECTORY_SEPARATOR . $file;
                    if (!is_file($full)) {
                        continue;
                    }
                    $mtime = @filemtime($full);
                    if ($mtime === false || $mtime < $since) {
                        continue;
                    }
                    $matched[$mtime . '_' . $file] = '/uploads/editor_images/' . $file;
                }
                if ($matched) {
                    ksort($matched);
                    $uploadedImages = array_values($matched);
                    if (count($uploadedImages) > 1) {
                        $uploadedImages = [end($uploadedImages)];
                    }
                    $uploadedImagesSource = 'scan_dir';
                    blog_debug_log('member_post_image.log', [
                        'event' => 'uploaded_images_from_scan_dir',
                        'req' => $debugReqId,
                        'uid' => $uid,
                        'since' => $since,
                        'dir' => $imgDir,
                        'count' => count($uploadedImages),
                        'list' => $uploadedImages,
                    ]);
                }
            }
        }
        
        if (!$uploadedImages) {
            try {
                $since = time() - 600;
                $stmt = $pdo->prepare("
                    SELECT path
                    FROM media_files
                    WHERE type = 'image'
                      AND uploader_id = :uid
                      AND created_at >= :since
                    ORDER BY created_at DESC, id DESC
                    LIMIT 3
                ");
                $stmt->execute([
                    ':uid' => $uid,
                    ':since' => $since,
                ]);
                $rows = $stmt->fetchAll() ?: [];
                $paths = [];
                foreach ($rows as $row) {
                    $url = trim((string)($row['path'] ?? ''));
                    if ($url !== '') {
                        $paths[] = $url;
                    }
                }
                $paths = array_values(array_unique($paths));
                if (count($paths) === 1) {
                    $uploadedImages = [$paths[0]];
                    $uploadedImagesSource = 'unique_media';
                    blog_debug_log('member_post_image.log', [
                        'event' => 'uploaded_images_from_unique_media',
                        'req' => $debugReqId,
                        'uid' => $uid,
                        'since' => $since,
                        'count' => count($uploadedImages),
                        'list' => $uploadedImages,
                    ]);
                }
            } catch (Throwable $e) {
                
            }
        }
    }

    if ($data['content_html'] !== '') {
        $rawHtml = $data['content_html'];
        $hasMedia = (bool)preg_match('/<(img|video|audio|iframe|embed|object|source|blockquote|pre|code|ul|ol|li|table|hr|h[1-6])\\b/i', $rawHtml);
        $plain = html_entity_decode(strip_tags($rawHtml), ENT_QUOTES, 'UTF-8');
        $plain = preg_replace('/[\\s\\x{00A0}\\x{200B}\\x{200C}\\x{200D}\\x{FEFF}]+/u', '', (string)$plain);
        $looksEmptyHtml = (bool)preg_match('/^\\s*(?:<p>\\s*(?:<br\\s*\\/?\\s*>|&nbsp;|&#160;|&#xA0;|\\x{FEFF})\\s*<\\/p>\\s*)+$/iu', $rawHtml);
        if (($plain === '' || $looksEmptyHtml) && !$hasMedia) {
            $data['content_html'] = '';
        }
    }

    if ($data['content_html'] !== '' && !preg_match('/<\\s*\\/?[a-z][^>]*>/i', $data['content_html'])) {
        $data['content_html'] = '<p>' . nl2br(h($data['content_html']), false) . '</p>';
    }

    if ($data['content_html'] === '' && $data['content_text'] !== '') {
        $data['content_html'] = '<p>' . nl2br(h($data['content_text'])) . '</p>';
    }

    blog_debug_log('member_post_image.log', [
        'event' => 'before_auto_append',
        'req' => $debugReqId,
        'uid' => $uid,
        'uploaded_images_source' => $uploadedImagesSource,
        'uploaded_images_count' => is_array($uploadedImages) ? count($uploadedImages) : null,
        'uploaded_images_list' => is_array($uploadedImages) ? $uploadedImages : null,
        'content_html_len' => strlen((string)$data['content_html']),
        'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
    ]);

    
    
    $autoAppended = [];
    if (!empty($uploadedImages) && is_array($uploadedImages)) {
        $safeImages = [];
        $prefix = '/uploads/editor_images/img' . $uid . '_';
        foreach ($uploadedImages as $u) {
            if (!is_string($u)) {
                continue;
            }
            $u = trim($u);
            if ($u === '') {
                continue;
            }
            
            if (strpos($u, $prefix) !== 0) {
                continue;
            }
            $safeImages[] = $u;
        }
        if ($safeImages) {
            $htmlNow = (string)$data['content_html'];
            
            if ($htmlNow !== '' && preg_match('/^\\s*(?:<p>\\s*(?:<br\\s*\\/?\\s*>|&nbsp;|&#160;|&#xA0;|\\x{FEFF})\\s*<\\/p>\\s*)+$/iu', $htmlNow)) {
                $htmlNow = '';
            }
            foreach ($safeImages as $u) {
                if ($htmlNow !== '' && strpos($htmlNow, $u) !== false) {
                    continue;
                }
                $htmlNow .= '<p><img src="' . h($u) . '" alt=""></p>';
                $autoAppended[] = $u;
            }
            if ($autoAppended) {
                $data['content_html'] = trim($htmlNow);
            }
        }
    }

    blog_debug_log('member_post_image.log', [
        'event' => 'after_auto_append',
        'req' => $debugReqId,
        'uid' => $uid,
        'appended' => $autoAppended,
        'content_html_len' => strlen((string)$data['content_html']),
        'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
    ]);

    if ($data['content_html'] !== '') {
        $data['content_html'] = normalize_hidden_blocks_before_save($data['content_html']);
        blog_debug_log('member_post_image.log', [
            'event' => 'after_normalize_hidden',
            'req' => $debugReqId,
            'uid' => $uid,
            'content_html_len' => strlen((string)$data['content_html']),
            'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
            'content_html_preview' => blog_debug_preview((string)$data['content_html']),
        ]);

        $data['content_html'] = sanitize_member_html($data['content_html']);
        blog_debug_log('member_post_image.log', [
            'event' => 'after_sanitize',
            'req' => $debugReqId,
            'uid' => $uid,
            'content_html_len' => strlen((string)$data['content_html']),
            'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
            'content_html_preview' => blog_debug_preview((string)$data['content_html']),
        ]);

        $data['content_html'] = normalize_html_newlines($data['content_html']);
        blog_debug_log('member_post_image.log', [
            'event' => 'after_normalize_newlines',
            'req' => $debugReqId,
            'uid' => $uid,
            'content_html_len' => strlen((string)$data['content_html']),
            'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
            'content_html_preview' => blog_debug_preview((string)$data['content_html']),
        ]);

        $data['content_html'] = str_replace(["\xEF\xBB\xBF", "在这里输入内容...", "在这里输入内容…"], '', $data['content_html']);
    }

    
    
    if (!empty($uploadedImages) && is_array($uploadedImages)) {
        $prefix = '/uploads/editor_images/img' . $uid . '_';
        $needAppend = [];
        foreach ($uploadedImages as $u) {
            if (!is_string($u)) {
                continue;
            }
            $u = trim($u);
            if ($u === '' || strpos($u, $prefix) !== 0) {
                continue;
            }
            if (strpos((string)$data['content_html'], $u) !== false) {
                continue;
            }
            $needAppend[] = $u;
        }
        if ($needAppend) {
            foreach ($needAppend as $u) {
                $data['content_html'] = rtrim((string)$data['content_html']) . '<p><img src="' . h($u) . '" alt=""></p>';
            }
            blog_debug_log('member_post_image.log', [
                'event' => 'final_reappend_images',
                'req' => $debugReqId,
                'uid' => $uid,
                'source' => $uploadedImagesSource ?? 'unknown',
                'appended' => $needAppend,
                'content_html_len' => strlen((string)$data['content_html']),
                'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
            ]);
        }
    }

    if ($data['content_html'] === '' && $data['content_text'] !== '') {
        $data['content_html'] = '<p>' . nl2br(h($data['content_text'])) . '</p>';
    }

    blog_debug_log('member_post_image.log', [
        'event' => 'before_validate',
        'req' => $debugReqId,
        'uid' => $uid,
        'content_html_len' => strlen((string)$data['content_html']),
        'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
        'content_html_preview' => blog_debug_preview((string)$data['content_html']),
        'content_text_len' => strlen((string)$data['content_text']),
        'errors_count' => count($errors),
        'errors' => $errors,
    ]);

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

    if (!$errors) {
        try {
            $now = time();
            $status = 'pending';
            $publishedAt = null;
            if ($autoApproveAfter > 0) {
                try {
                    $stmt = $pdo->prepare("
                        SELECT COUNT(*) FROM articles
                        WHERE author_id = :uid AND status = 'published'
                    ");
                    $stmt->execute([':uid' => $uid]);
                    $publishedCount = (int)$stmt->fetchColumn();
                    if ($publishedCount >= $autoApproveAfter) {
                        $status = 'published';
                        $publishedAt = $now;
                    }
                } catch (Throwable $e) {
                    
                }
            }

            $stmt = $pdo->prepare("
                INSERT INTO articles
                    (title, slug, content_html, summary, category_id,
                     author_id, status, is_recommended, is_home_candidate,
                     view_count, like_count, comment_count,
                     created_at, updated_at, published_at)
                VALUES
                    (:title, NULL, :content_html, :summary, :category_id,
                     :author_id, :status, 0, 0,
                     0, 0, 0,
                     :created_at, :updated_at, :published_at)
            ");
            $stmt->execute([
                ':title'        => $data['title'],
                ':content_html' => $data['content_html'],
                ':summary'      => $data['summary'],
                ':category_id'  => $data['category_id'] ?: null,
                ':author_id'    => $uid,
                ':status'       => $status,
                ':created_at'   => $now,
                ':updated_at'   => $now,
                ':published_at' => $publishedAt,
            ]);

            $articleId = (int)$pdo->lastInsertId();

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

            $savedArticleId = $articleId;
            $savedStatus = $status;

            blog_debug_log('member_post_image.log', [
                'event' => 'submit_saved',
                'req' => $debugReqId,
                'uid' => $uid,
                'article_id' => $articleId,
                'status' => $status,
                'content_html_len' => strlen((string)$data['content_html']),
                'content_html_has_img' => preg_match('/<img\\b/i', (string)$data['content_html']) ? 1 : 0,
                'uploaded_images_source' => $uploadedImagesSource ?? 'unknown',
                'uploaded_images_count' => isset($uploadedImages) && is_array($uploadedImages) ? count($uploadedImages) : null,
                'uploaded_images_list' => isset($uploadedImages) && is_array($uploadedImages) ? $uploadedImages : null,
            ]);

            
            if (session_status() === PHP_SESSION_ACTIVE) {
                $_SESSION['last_post_id'] = $articleId;
                $_SESSION['last_post_uid'] = $uid;
                $_SESSION['last_post_time'] = $now;
            }

            
            if (!empty($_SESSION['recent_uploads']) && is_array($_SESSION['recent_uploads'])) {
                $keep = [];
                foreach ($_SESSION['recent_uploads'] as $item) {
                    if (!is_array($item)) {
                        continue;
                    }
                    if (($item['type'] ?? '') === 'image' && (int)($item['uid'] ?? 0) === $uid) {
                        continue;
                    }
                    $keep[] = $item;
                }
                $_SESSION['recent_uploads'] = $keep;
            }
            if (isset($_SESSION['member_post_started_at'])) {
                unset($_SESSION['member_post_started_at']);
            }

            $saved = true;
            $data = [
                'title'        => '',
                'summary'      => '',
                'content_html' => '',
                'content_text' => '',
                'category_id'  => 0,
                'tags_text'    => '',
            ];
        } catch (Throwable $e) {
            $errors[] = '投稿失败：' . $e->getMessage();
            blog_debug_log('member_post_image.log', [
                'event' => 'submit_failed',
                'req' => $debugReqId,
                'uid' => $uid,
                'error' => blog_debug_preview($e->getMessage()),
            ]);
        }
    }
}

$memberActivity = load_member_activity($currentUser);
$myArticles     = $memberActivity['myArticles'];
$myReplies      = $memberActivity['myReplies'];

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>发布文章 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="<?php echo h($siteDescription); ?>">
    <style>
        :root {
            --bg: #f5f5f7;
            --bg-elevated: #ffffff;
            --bg-header: #ffffff;
            --border-subtle: #e5e7eb;
            --text-main: #111827;
            --text-muted: #6b7280;
            --accent: #2563eb;
            --accent-soft: #dbeafe;
            --accent-strong: #1d4ed8;
        }
        body[data-theme="dark"] {
            --bg: #0f172a;
            --bg-elevated: #111827;
            --bg-header: #020617;
            --border-subtle: #1f2937;
            --text-main: #e5e7eb;
            --text-muted: #9ca3af;
            --accent: #3b82f6;
            --accent-soft: #1d4ed8;
            --accent-strong: #60a5fa;
        }
        html, body { height:100%;  margin:0; padding:0; }
        body { margin:0; padding:0; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif; background:var(--bg); color:var(--text-main); }
        a { color:var(--accent); text-decoration:none; }
        a:hover { text-decoration:underline; }

        .header { background:var(--bg-header); border-bottom:1px solid var(--border-subtle);  margin:0;  padding:0;  margin-top:-18px; padding-top:18px; }
        .header-inner { max-width:1200px; margin:0 auto; padding:0 16px 6px; display:grid; grid-template-columns:220px minmax(0,1fr) 260px; gap:16px; align-items:flex-start; }
        .logo { font-size:20px; font-weight:700; white-space:nowrap; }
        .subtitle { font-size:12px; color:var(--text-muted); }
                .search-box { width:100%; min-width:0; display:flex; align-items:center; gap:0; }
        .search-input { flex:1; min-width:0; position:relative; }
        .search-input input { width:100%; padding:6px 10px; border-radius:999px; border:1px solid var(--border-subtle); background:var(--bg); color:var(--text-main); font-size:14px; }
                .search-box form, form.search-box { width:100%; display:flex; align-items:center; height:40px; background:var(--bg); border:1px solid var(--border-subtle); border-radius:999px; overflow:hidden; }
.search-box form:focus-within, form.search-box:focus-within { border-color:var(--accent); box-shadow:0 0 0 2px rgba(37,99,235,0.08); }
.search-box input[type="text"], form.search-box input[type="text"] { flex:1; min-width:0; height:100%; padding:0 12px; border:0; background:transparent; color:var(--text-main); font-size:14px; }
.search-box input[type="text"]::placeholder, form.search-box input[type="text"]::placeholder { color:var(--text-muted); }
.search-btn { min-width:72px; height:100%; white-space:nowrap; padding:0 16px; border:0; border-left:1px solid var(--border-subtle); background:linear-gradient(135deg, var(--accent), var(--accent-strong)); color:#fff; font-size:13px; font-weight:600; display:inline-flex; align-items:center; justify-content:center; cursor:pointer; transition:filter .12s, transform .12s; }
.search-btn:hover { filter:brightness(1.06); transform:none; }
        .header-actions { display:flex; align-items:center; justify-content:flex-end; gap:8px; flex-wrap:wrap; }
        .btn, .btn-ghost { font-size:13px; padding:6px 10px; border-radius:999px; border:1px solid var(--accent); cursor:pointer; }
        .btn { background:var(--accent-soft); color:var(--accent-strong); }
        .btn-ghost { background:transparent; color:var(--text-muted); border-color:transparent; }

        .page { max-width:1200px; margin:0 auto; padding:16px; }
        .layout { display:grid; grid-template-columns:220px minmax(0,1fr) 260px; gap:16px; }
        .column { display:flex; flex-direction:column; gap:12px; }

        .card { background:var(--bg-elevated); border-radius:6px; border:1px solid var(--border-subtle); padding:10px 12px; }
        .card-title { font-size:14px; font-weight:600; margin-bottom:6px; position:relative; padding-left:6px; }

        ul { list-style:none; margin:0; padding:0; }
        li { font-size:12px; padding:2px 0; }
        .small-text { font-size:11px; color:var(--text-muted); }

        .category-name a { color:var(--text-main); font-weight:500; }
        .category-pill { display:flex; align-items:center; justify-content:flex-start; padding:4px 8px; border-radius:999px; background:rgba(37,99,235,0.05); margin-bottom:4px; transition:background 0.15s, transform 0.15s; }
        .category-pill:hover { background:rgba(37,99,235,0.12); transform:translateX(2px); }
        .category-count { font-size:11px; color:var(--text-muted); }
        .category-count-num { display:inline-block; min-width:18px; height:16px; line-height:16px; padding:0 5px; border-radius:999px; text-align:center; font-size:10px; font-weight:600; font-variant-numeric:tabular-nums; background:rgba(37,99,235,0.12); color:var(--accent-strong); }

        .contact-list li { display:flex; align-items:center; margin-bottom:4px; }
        .contact-icon { width:20px; height:20px; border-radius:999px; background:rgba(37,99,235,0.12); color:var(--accent-strong); display:flex; align-items:center; justify-content:center; font-size:12px; margin-right:6px; }
        .contact-text { flex:1; }
        .friend-links { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:6px 8px; }
        .friend-links li { padding:0; }
        .friend-links + .small-text { text-align:left; }
        .friend-links li a {
            text-align:left; display:inline-flex; align-items:center; width:auto; max-width:100%; padding:4px 8px; border-radius:999px; background:rgba(37,99,235,0.04); transition:background 0.15s, transform 0.15s; }
        .friend-links li a:hover { background:rgba(37,99,235,0.12); transform:translateX(2px); }
        .new-sites-list li a { display:inline-block; padding:3px 0; }
        .list-compact li { border-bottom:1px dashed #e5e7eb; }
        .site-stats-list { list-style:none; margin:0; padding:0; border:0; border-radius:0; background:transparent; }
        .site-stats-item { display:flex; align-items:center; justify-content:space-between; min-height:34px; padding:0 2px; border-bottom:1px solid #eef2f7; font-size:13px; }
        .site-stats-item:last-child { border-bottom:none; }
        .site-stats-label { display:inline-flex; align-items:center; gap:8px; color:var(--text-muted); }
        .site-stats-value { color:var(--text-main); font-size:13px; font-weight:700; font-variant-numeric:tabular-nums; }
        .site-stats-item-highlight .site-stats-value { color:var(--accent-strong); }
        .site-stats-icon { width:14px; height:14px; flex:0 0 14px; display:inline-flex; align-items:center; justify-content:center; color:#64748b; }
        .site-stats-item-highlight .site-stats-icon { color:var(--accent); }
        .site-stats-icon svg { width:14px; height:14px; display:block; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; }
        body[data-theme="dark"] .site-stats-item { border-bottom-color:#1f2937; }
        body[data-theme="dark"] .site-stats-icon { color:#94a3b8; }

        
        .form-row { display:flex; gap:8px; margin-bottom:8px; }
        .form-row label { width:60px; font-size:13px; }
        .form-row input,
        .form-row select,
        .form-row textarea {
            flex:1;
            padding:4px 6px;
            border-radius:4px;
            border:1px solid #d1d5db;
            font-size:13px;
        }
        .editor-row #content_html {
            width: 100%;
        }
        .editor-row .tox.tox-tinymce {
            flex: 1 1 auto;
            width: 100% !important;
            max-width: none;
        }
        .submit-btn { border-radius:999px; border:1px solid var(--accent); background:var(--accent-soft); color:var(--accent-strong); font-size:13px; padding:6px 12px; cursor:pointer; margin-top:8px; }

        .errors { background:#fef2f2; border:1px solid #fecaca; color:#991b1b; padding:6px 8px; border-radius:4px; font-size:12px; margin-bottom:10px; }
        .success { background:#ecfdf5; border:1px solid #bbf7d0; color:#166534; padding:6px 8px; border-radius:4px; font-size:12px; margin-bottom:10px; }

                .member-card-header {
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:8px;
            margin-bottom:6px;
        }
                .member-card-title-main {
            font-size:14px;
            font-weight:600;
        }
                .member-card-title-sub {
            display:inline-flex;
            align-items:center;
            height:20px;
            padding:0 8px;
            border-radius:999px;
            font-size:11px;
            color:#166534;
            background:#dcfce7;
            border:1px solid #86efac;
            line-height:20px;
            white-space:nowrap;
        }
                .member-actions {
            display:grid;
            grid-template-columns:repeat(3, minmax(0, 1fr));
            gap:8px;
            margin-top:8px;
        }
        .member-actions .btn {
            display:flex;
            align-items:center;
            justify-content:center;
            height:30px;
            margin-top:0;
            padding:0 8px;
            font-size:12px;
            text-align:center;
            white-space:nowrap;
        }
        .member-actions .btn.btn-logout {
            border-color:#fdba74;
            background:#fff7ed;
            color:#9a3412;
        }
        .member-welcome {
            margin:0 0 8px;
            font-size:12px;
            color:var(--text-muted);
            line-height:1.5;
        }
        .member-more {
            margin-top:6px;
            text-align:right;
            font-size:12px;
            color:var(--text-muted);
        }
        .member-guest-actions { display:flex; gap:8px; margin-top:6px; }
        .member-guest-actions .btn { flex:1; font-size:12px; padding:5px 0; }

        .tag-selector { display:flex; flex-wrap:wrap; margin-top:4px; }
        .tag-choice {
            border-radius:999px;
            border:1px solid var(--border-subtle);
            background:rgba(37,99,235,0.04);
            color:var(--text-main);
            font-size:12px;
            padding:2px 8px;
            cursor:pointer;
            margin:2px 4px 2px 0;
        }
        .tag-choice.is-selected {
            background:var(--accent-soft);
            border-color:var(--accent);
            color:var(--accent-strong);
        }

        .site-footer { margin-top:16px; border-top:1px solid var(--border-subtle); background:var(--bg-header); color:var(--text-muted); font-size:12px; }
        .site-footer .footer-inner { max-width:1200px; margin:0 auto; padding:10px 16px 16px; text-align:center;
            display:flex;
            justify-content:center;
            align-items:center; }
        .site-footer a { color:var(--accent); }

        @media (max-width:768px) {
            .layout { grid-template-columns:minmax(0,1fr); }
            .header-inner { grid-template-columns:minmax(0,1fr); }
        .header-actions { justify-content:flex-start; }
        }
        .hidden-comment-block {
            border: 1px dashed #f59e0b;
            background: #fffbeb;
            color: #111827;
            padding: 8px 10px;
            border-radius: 6px;
            margin: 8px 0;
        }
        .hidden-comment-block p {
            margin: 0 0 6px;
        }
        .hidden-comment-block p:last-child {
            margin-bottom: 0;
        }
        .hidden-comment-block strong {
            color: #b45309;
        }
        .hidden-comment-block .hidden-label {
            font-weight: 600;
        }
        .hidden-comment-block .hidden-label[contenteditable="false"] {
            user-select: none;
        }
        .hidden-comment-block .hidden-content[data-empty="1"]::before {
            content: attr(data-placeholder);
            color: #9ca3af;
        }
        [data-hidden-marker^="comment-only"] {
            display: none !important;
        }
        .attach-input {
            display: none;
        }
    </style>
</head>
<body style="margin:0;padding:0;" data-theme="light"><header class="header">
    <div class="header-inner">
        <div>
            <div class="logo"><?php echo h($siteTitle); ?></div>
            <div class="subtitle"><?php echo h($siteSubtitle); ?></div>
        </div>
        <div class="search-box">
            <div class="search-input">
                <form method="get" action="search.php">
                    <input type="text" name="q" placeholder="搜索文章（标题/正文）">
                    <button type="submit" class="search-btn">搜索</button>
                </form>
            </div>
        </div>
        <div class="header-actions">
            <button class="btn-ghost" id="theme-toggle">夜间模式</button>
            <a class="btn" href="member_post.php">发布文章</a>
            <button class="btn" id="fav-btn">收藏本站</button>
        </div>
    </div>
</header>

<main class="page">
    <div class="layout">
        <aside class="column">
            <section class="card">
                <div class="card-title">分类导航</div>
                <ul>
                    <li>
                        <div class="category-pill">
                            <span class="category-name">
                                <?php echo render_home_nav_link('index.php'); ?>
                            </span>
                            <span class="category-count">&nbsp;</span>
                        </div>
                    </li>
                    <?php foreach ($categories as $cat): ?>
                        <li>
                            <div class="category-pill">
                                <span class="category-name">
                                    <a href="category.php?id=<?php echo (int)$cat['id']; ?>">
                                        <?php if (!empty($cat['icon_path'])): ?>
                                            <img src="<?php echo h($cat['icon_path']); ?>" alt="" style="width:16px;height:16px;border-radius:3px;vertical-align:-3px;margin-right:4px;">
                                        <?php endif; ?>
                                        <?php echo h($cat['name']); ?>
                                    </a>
                                </span>
                                <span class="category-count category-count-num"><?php echo (int)$cat['article_count']; ?></span>
                            </div>
                        </li>
                    <?php endforeach; ?>
                    <?php if (!$categories): ?><li class="small-text">暂无分类</li><?php endif; ?>
                </ul>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderContact; ?>;<?php if (!$showContactCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleContactCard); ?></div>
                <ul class="contact-list">
                    <?php if (!empty($contactItems)): ?>
                        <?php foreach ($contactItems as $ci): ?>
                            <li>
                                <div class="contact-icon"><?php echo h($ci['icon']); ?></div>
                                <div class="contact-text small-text"><?php echo h($ci['label']); ?>：<?php echo h($ci['value']); ?></div>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="small-text">可在后台“站点设置 &gt; 联系方式”中配置联系方式。</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderImportantLinks; ?>;<?php if (!$showImportantLinksCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleImportantLinksCard); ?></div>
                <ul class="friend-links">
                    <?php if ($importantFriendLinks): foreach ($importantFriendLinks as $fl): ?>
                        <li>
                            <a href="<?php echo h($fl['url']); ?>" target="_blank"><?php echo h($fl['name']); ?></a>
                        </li>
                    <?php endforeach; else: ?>
                        <li class="small-text">可在后台“友链与最新网址”中添加友情链接</li>
                    <?php endif; ?>
                </ul>
                <div class="small-text" style="margin-top:4px;">
                    <a href="links.php">查看全部友链 / 提交申请</a>
                </div>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderNewSites; ?>;<?php if (!$showNewSitesCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleNewSitesCard); ?></div>
                <ul class="new-sites-list">
                    <?php if ($newSites): foreach ($newSites as $ns): ?>
                        <li><?php echo render_new_site_anchor($ns); ?></li>
                    <?php endforeach; else: ?>
                        <li class="small-text">可在后台添加防封用域名</li>
                    <?php endif; ?>
                </ul>
            </section>

            
            <section class="card" style="order: <?php echo (int)$sidebarOrderTags; ?>;">
                <div class="card-title">热门标签</div>
                <div>
                    <?php if ($tags): foreach ($tags as $t): ?>
                        <a class="small-text" href="tag.php?id=<?php echo (int)$t['id']; ?>" style="margin-right:4px;">#<?php echo h($t['name']); ?></a>
                    <?php endforeach; else: ?>
                        <span class="small-text">暂无标签</span>
                    <?php endif; ?>
                </div>
            </section>
</aside>

        <section class="column">
            <section class="card">
                <div class="card-title">发布文章</div>
                <?php if ($errors): ?>
                    <div class="errors">
                        <?php foreach ($errors as $err): ?>
                            <div><?php echo h($err); ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <?php if ($saved && !$errors): ?>
                    <?php if ($savedStatus === 'published' && $savedArticleId > 0): ?>
                        <div class="success">
                            发布成功，已直接发布：
                            <a href="post.php?id=<?php echo (int)$savedArticleId; ?>" target="_blank" rel="noopener">查看文章</a>
                        </div>
                    <?php else: ?>
                        <div class="success">投稿已提交，等待管理员审核</div>
                    <?php endif; ?>
                <?php endif; ?>

                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                    <input type="hidden" id="content_text" name="content_text" value="<?php echo h($data['content_text']); ?>">
                    <input type="hidden" id="uploaded_images" name="uploaded_images" value="<?php echo h($uploadedImagesRaw); ?>">

                    <div class="form-row">
                        <label for="title">标题</label>
                        <input type="text" id="title" name="title" value="<?php echo h($data['title']); ?>" required>
                    </div>

                    <div class="form-row">
                        <label for="category_id">分类</label>
                        <select id="category_id" name="category_id">
                            <?php if (!$categoriesForSelect): ?>
                                <option value="0" disabled>暂无分类</option>
                            <?php else: ?>
                                <?php foreach ($categoriesForSelect as $cat): ?>
                                    <option value="<?php echo (int)$cat['id']; ?>" <?php echo $data['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo h($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="form-row">
                        <label for="summary">摘要</label>
                        <textarea id="summary" name="summary" rows="2" placeholder="可选，建议 2-3 句即可"><?php echo h($data['summary']); ?></textarea>
                    </div>

                    <div class="form-row editor-row">
                        <label for="content_html">正文</label>
                        <textarea id="content_html" name="content_html" rows="14"><?php echo h($data['content_html']); ?></textarea>
                        <input type="file" id="image-input" class="attach-input" accept="image/*">
                        <input type="file" id="attach-input" class="attach-input" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.md,.zip,.rar,.7z">
                        <input type="file" id="video-input" class="attach-input" accept="video/mp4,video/webm,video/ogg">
                    </div>

                    <div class="small-text">
                        已接入富文本编辑器（TinyMCE），支持图片、附件与视频上传<br>
                        图片支持格式：jpg/png/gif/webp，大小不超过 2MB<br>
                        附件支持格式：pdf/doc/docx/xls/xlsx/ppt/pptx/txt/md/zip/rar/7z，大小不超过 10MB<br>
                        视频支持格式：mp4/webm/ogg，大小不超过 50MB<br>
                        点击工具栏的“隐藏内容”可插入高亮块（可编辑）<br>
                        如需设置“隐藏内容 · 评论可见”的区域，可在正文中使用以下标记包裹需要隐藏的内容<br>
                        <code>&lt;!--hidden:comment-only:start--&gt;这里是隐藏内容块&lt;!--hidden:comment-only:end--&gt;</code><br>
                        同一篇文章中可以多次使用上述标记；访客在本篇文章下至少有一条“已通过审核”的评论后，才能看到这些隐藏内容。
                    </div>

                    <div class="form-row" style="margin-top:10px;">
                        <label for="tags_text">标签</label>
                        <input type="text" id="tags_text" name="tags_text" value="<?php echo h($data['tags_text']); ?>" placeholder="多个标签用逗号或空格分隔">
                    </div>
                    <?php if ($allTags): ?>
                        <div class="small-text">点击下面已有标签可快速选择（可多选）</div>
                        <div class="tag-selector">
                            <?php
                            $currentTags = trim((string)$data['tags_text']);
                            foreach ($allTags as $t):
                                $name = (string)$t['name'];
                                $isSelected = false;
                                if ($currentTags !== '') {
                                    $pattern = '/(^|[，\\s])' . preg_quote($name, '/') . '([，\\s]|$)/u';
                                    $isSelected = (bool)preg_match($pattern, $currentTags);
                                }
                            ?>
                                <button type="button"
                                        class="tag-choice<?php echo $isSelected ? ' is-selected' : ''; ?>"
                                        data-tag="<?php echo h($name); ?>">
                                    <?php echo h($name); ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <button type="submit" class="submit-btn">提交投稿</button>
                </form>
            </section>
        </section>

        <aside class="column">
            <section class="card">
                <div class="member-card-header">
                    <div class="member-card-title-main">会员中心</div>
                    <?php if ($currentUser): ?>
                        <div class="member-card-title-sub">已登录</div>
                    <?php endif; ?>
                </div>
                <?php if ($currentUser): ?>
                    <div class="member-welcome">欢迎，<?php echo h($currentUser['nickname'] ?? '会员'); ?>（ID：<?php echo (int)$currentUser['id']; ?>）</div>
                    <div class="member-actions">
                        <a class="btn" href="profile.php">资料 / 头像</a>
                        <a class="btn" href="member_password.php">密码修改</a>
                        <a class="btn btn-logout" href="logout.php">退出登录</a>
                    </div>

                    <?php if ($myArticles): ?>
                        <div class="small-text" style="margin-top:6px;">我的主题</div>
                        <ul class="list-compact">
                            <?php foreach ($myArticles as $ma): ?>
                                <li>
                                    <a href="post.php?id=<?php echo (int)$ma['id']; ?>">
                                        <?php echo h($ma['title']); ?>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>

                    <?php if ($myReplies): ?>
                        <div class="small-text" style="margin-top:6px;">我的回复</div>
                        <ul class="list-compact">
                            <?php foreach ($myReplies as $mr): ?>
                                <?php $snippet = mb_substr($mr['content'], 0, 20, 'UTF-8'); ?>
                                <li>
                                    <a href="post.php?id=<?php echo (int)$mr['article_id']; ?>#comment-<?php echo (int)$mr['id']; ?>">
                                        <?php echo h($mr['article_title'] ?: '正文'); ?>：<?php echo h($snippet); ?>...
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                    <div class="member-more">
                        <a href="member_center.php">查看更多 ></a>
                    </div>
                <?php else: ?>
                    <div class="member-guest-actions">
                        <a class="btn" href="login.php">会员登录</a>
                        <a class="btn btn-ghost" href="register.php">注册账号</a>
                    </div>
                <?php endif; ?>
            </section>

            <section class="card">
                <div class="card-title">最新评论</div>
                <ul class="list-compact">
                    <?php if ($recentComments): foreach ($recentComments as $c): ?>
                        <li>
                            <?php $name = $c['is_guest'] ? ($c['guest_name'] ?: '匿名') : ($c['nickname'] ?: '会员'); ?>
                            <?php $text = mb_substr($c['content'], 0, 30, 'UTF-8'); ?>
                            <?php echo h($name); ?>：<?php echo h($text); ?>...
                        </li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无评论</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">最多点赞</div>
                <ul class="list-compact">
                    <?php if ($mostLikedArticles): foreach ($mostLikedArticles as $ma): ?>
                        <li><a href="post.php?id=<?php echo (int)$ma['id']; ?>"><?php echo h($ma['title']); ?></a>（<?php echo (int)$ma['like_count']; ?> 赞）</li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无点赞数据</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">最热文章</div>
                <ul class="list-compact">
                    <?php if ($hotArticles): foreach ($hotArticles as $ha): ?>
                        <li><a href="post.php?id=<?php echo (int)$ha['id']; ?>"><?php echo h($ha['title']); ?></a>（<?php echo (int)$ha['view_count']; ?> 浏览 / <?php echo (int)$ha['like_count']; ?> 赞）</li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无热门文章</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">站点统计</div>
                <ul class="site-stats-list">
                    <li class="site-stats-item site-stats-item-highlight">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="4"></circle><path d="M4 21c1.5-4 4.2-6 8-6s6.5 2 8 6"></path></svg></span>今日访客</span>
                        <span class="site-stats-value"><?php echo (int)$statsToday['uv']; ?></span>
                    </li>
                    <li class="site-stats-item site-stats-item-highlight">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M2 12s3.8-6 10-6 10 6 10 6-3.8 6-10 6-10-6-10-6"></path><circle cx="12" cy="12" r="2.8"></circle></svg></span>今日浏览</span>
                        <span class="site-stats-value"><?php echo (int)$statsToday['pv']; ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><line x1="5" y1="20" x2="19" y2="20"></line><rect x="6" y="11" width="2.8" height="7"></rect><rect x="11" y="8" width="2.8" height="10"></rect><rect x="16" y="5" width="2.8" height="13"></rect></svg></span>总浏览量</span>
                        <span class="site-stats-value"><?php echo (int)$statsTotal['pv']; ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M7 3h7l5 5v13H7z"></path><path d="M14 3v5h5"></path></svg></span>文章数目</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['articles'] ?? 0); ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M4 6h16v9H7l-3 3z"></path></svg></span>评论数目</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['comments'] ?? 0); ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"></circle><path d="M12 8v4l2.8 1.6"></path></svg></span>运行天数</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['runtime_days'] ?? 1); ?> 天</span>
                    </li>
                </ul>
            </section></aside>
    </div>
</main>

<footer class="site-footer">
    <div class="footer-inner">
        <div class="footer-main">
            <?php echo h($siteFooterBrand); ?> &copy; <?php echo date('Y'); ?>
            <?php if ($siteFooterOfficialUrl && $siteFooterOfficialText): ?>
                · 官方站点：<a href="<?php echo h($siteFooterOfficialUrl); ?>" target="_blank"><?php echo h($siteFooterOfficialText); ?></a>
            <?php endif; ?>
        </div>
    </div>
</footer>

<script src="/assets/tinymce/tinymce.min.js"></script>
<script>
    
    (function () {
        if (!window.tinymce) return;
        var textarea = document.getElementById('content_html');
        if (!textarea) return;

        var csrfToken = <?php echo json_encode(csrf_token()); ?>;
        var imageInput = document.getElementById('image-input');
        var attachInput = document.getElementById('attach-input');
        var videoInput = document.getElementById('video-input');
        var contentTextInput = document.getElementById('content_text');
        var uploadedImagesInput = document.getElementById('uploaded_images');
        var uploadedImages = [];
        var editorInstance = null;
        var uploadInProgress = 0;
        var submitBtn = document.querySelector('.submit-btn');

        function setSubmitBusy(busy) {
            if (!submitBtn) return;
            if (busy) {
                submitBtn.disabled = true;
                submitBtn.textContent = '上传中...';
            } else {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交投稿';
            }
        }

        function beginUpload() {
            uploadInProgress++;
            setSubmitBusy(true);
        }

        function endUpload() {
            uploadInProgress = Math.max(0, uploadInProgress - 1);
            if (uploadInProgress === 0) {
                setSubmitBusy(false);
            }
        }

        setSubmitBusy(false);

        if (uploadedImagesInput && uploadedImagesInput.value) {
            try {
                var parsedImages = JSON.parse(uploadedImagesInput.value);
                if (Array.isArray(parsedImages)) {
                    uploadedImages = parsedImages.filter(function (u) { return typeof u === 'string' && u.trim(); });
                }
            } catch (e) {}
        }

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

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

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

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

        function updateUploadedImagesInput(list) {
            if (!uploadedImagesInput) return;
            try {
                uploadedImagesInput.value = JSON.stringify(list || []);
            } catch (e) {
                uploadedImagesInput.value = '';
            }
        }

        function addUploadedImage(url) {
            var u = String(url || '').trim();
            if (!u) return;
            if (uploadedImages.indexOf(u) === -1) {
                uploadedImages.push(u);
            }
            updateUploadedImagesInput(uploadedImages);
        }

        function syncUploadedImagesFromHtml(html) {
            if (!uploadedImagesInput) return;
            var list = [];
            String(html || '').replace(/<img\b[^>]*?src=["']([^"']+)["'][^>]*>/ig, function (_, src) {
                if (src && list.indexOf(src) === -1) list.push(src);
                return _;
            });
            uploadedImages = list;
            updateUploadedImagesInput(uploadedImages);
        }

        function syncText(editor) {
            if (!contentTextInput) return;
            var text = editor.getContent({ format: 'text' }) || '';
            text = text.replace(/在这里输入内容...?\.?\.?/g, '').trim();
            contentTextInput.value = text;
        }

        function syncHtml(editor) {
            if (!textarea || !editor) return;
            textarea.value = editor.getContent() || '';
        }

        function syncAll(editor) {
            if (!editor) return;
            cleanHiddenBlocks(editor);
            syncHtml(editor);
            syncText(editor);
            syncUploadedImagesFromHtml(editor.getContent());
            if (typeof editor.save === 'function') {
                editor.save();
            }
        }

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

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

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

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

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

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

        var form = textarea.closest('form');
        if (form) {
            form.addEventListener('submit', function (e) {
                if (uploadInProgress > 0) {
                    e.preventDefault();
                    alert('文件正在上传，请等待上传完成后再提交。');
                    return;
                }

                if (window.tinymce) {
                    tinymce.triggerSave();
                    var ed = getEditor();
                    if (ed) {
                        syncAll(ed);
                    }
                }
            });
        }
    })();
    
    (function () {
        var key  = 'lzblog-theme';
        var body = document.body;
        var btnTheme = document.getElementById('theme-toggle');
        var btnFav   = document.getElementById('fav-btn');

        function applyTheme(theme) {
            body.setAttribute('data-theme', theme);
            if (btnTheme) {
                btnTheme.textContent = theme === 'dark' ? '日间模式' : '夜间模式';
            }
        }

        var saved = localStorage.getItem(key);
        applyTheme(saved === 'dark' ? 'dark' : 'light');

        if (btnTheme) {
            btnTheme.addEventListener('click', function () {
                var next = body.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
                localStorage.setItem(key, next);
                applyTheme(next);
            });
        }

                    if (btnFav) {
                        btnFav.addEventListener('click', function () {
                            alert('请使用浏览器的收藏功能（例如：按 Ctrl + D）来收藏本站。');
                        });
                    }
    })();

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

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

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

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

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