<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include_once __DIR__ . '/../inc/static_cache.php';
include_once __DIR__ . '/../inc/content_center.php';

$domains = is_file(__DIR__ . '/../config/domain.php') ? include __DIR__ . '/../config/domain.php' : array();
if(!is_array($domains)) $domains = array();
$themeMap = admin_site_themes();
if(!$themeMap){
    foreach($domains as $cfg){
        if(!empty($cfg['theme'])) $themeMap[$cfg['theme']] = $cfg['theme'];
    }
}
$themes = array_keys($themeMap);
$host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
$host = explode(':', $host)[0];
$currentTheme = $domains[$host]['theme'] ?? ($themes[0] ?? 'industrial');

$channels = array('news'=>'新闻资讯','product'=>'产品服务','case'=>'客户案例','faq'=>'常见问题');
$scopes = array('site'=>'当前站点','theme'=>'当前主题','global'=>'全部主题');
$statuses = array('draft'=>'草稿','pending'=>'待发布','published'=>'已发布');

$msg = '';
$error = '';
$lastPostArticle = array();
$lastPostScope = '';
$lastPostTarget = '';
$lastPostChannel = '';
$lastPostStatus = '';
$lastPostPublishMode = '';

function cc_upload_image_file($file){
    if(empty($file) || !isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) return array('ok'=>false, 'empty'=>true, 'error'=>'');
    if($file['error'] !== UPLOAD_ERR_OK) return array('ok'=>false, 'error'=>'图片上传失败，请重新选择文件。');
    if(($file['size'] ?? 0) > 5 * 1024 * 1024) return array('ok'=>false, 'error'=>'图片不能超过 5MB。');
    $tmp = $file['tmp_name'] ?? '';
    if($tmp === '' || !is_uploaded_file($tmp)) return array('ok'=>false, 'error'=>'上传文件无效。');
    $info = @getimagesize($tmp);
    if(!$info || empty($info['mime'])) return array('ok'=>false, 'error'=>'请选择有效图片文件。');
    $map = array('image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp','image/gif'=>'gif');
    if(!isset($map[$info['mime']])) return array('ok'=>false, 'error'=>'仅支持 JPG、PNG、WEBP、GIF 图片。');
    $sub = date('Ym');
    $dir = __DIR__ . '/../assets/uploads/content_center/' . $sub;
    if(!is_dir($dir) && !@mkdir($dir, 0777, true)) return array('ok'=>false, 'error'=>'上传目录创建失败，请检查权限。');
    $name = 'cc-' . date('YmdHis') . '-' . mt_rand(1000,9999) . '.' . $map[$info['mime']];
    $target = $dir . '/' . $name;
    if(!move_uploaded_file($tmp, $target)) return array('ok'=>false, 'error'=>'图片保存失败，请检查 assets/uploads 目录权限。');
    return array('ok'=>true, 'url'=>'/assets/uploads/content_center/' . $sub . '/' . $name);
}

if($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload_content_image'){
    header('Content-Type: application/json; charset=utf-8');
    $ret = cc_upload_image_file($_FILES['image_file'] ?? array());
    echo json_encode($ret, JSON_UNESCAPED_UNICODE);
    exit;
}

function cc_admin_count($dir){
    return is_dir($dir) ? count(glob(rtrim($dir, '/') . '/*.php')) : 0;
}

function cc_datetime_local_value($value){
    $ts = strtotime((string)$value);
    return $ts ? date('Y-m-d\TH:i:s', $ts) : date('Y-m-d\TH:i:s', time() + 3600);
}

function cc_content_stats($records, $channels, $scopes){
    $stats = array();
    foreach($records as $row){
        $scope = $row['scope'] ?? 'site';
        $channel = $row['channel'] ?? 'news';
        if(!isset($channels[$channel])) $channel = 'news';
        $target = $row['target'] ?? '';
        $key = $scope . '|' . $target . '|' . $channel;
        if(!isset($stats[$key])){
            $stats[$key] = array(
                'scope' => $scope,
                'scope_label' => $scopes[$scope] ?? $scope,
                'target' => $target,
                'channel' => $channel,
                'total' => 0,
                'draft' => 0,
                'pending' => 0,
                'published' => 0,
            );
        }
        $stats[$key]['total']++;
        $status = $row['status'] ?? 'published';
        if(isset($stats[$key][$status])) $stats[$key][$status]++;
    }
    uasort($stats, function($a, $b){
        return strcmp($a['scope'] . $a['target'] . $a['channel'], $b['scope'] . $b['target'] . $b['channel']);
    });
    return $stats;
}

function cc_article_status($publishMode, $statusInput){
    $statusInput = trim((string)$statusInput);
    if(in_array($statusInput, array('draft','pending','published'), true)) return $statusInput;
    return $publishMode === 'schedule' ? 'pending' : 'published';
}

function cc_paginate_items($items, $page, $pageSize){
    $total = count($items);
    $pageSize = max(10, min(100, intval($pageSize)));
    $pages = max(1, (int)ceil($total / $pageSize));
    $page = max(1, min($pages, intval($page)));
    return array(array_slice($items, ($page - 1) * $pageSize, $pageSize), $total, $pages, $page, $pageSize);
}

function cc_page_url($pageNo, $pageParam='page'){
    $params = $_GET;
    $params[$pageParam] = $pageNo;
    return cms_admin_url('content_center.php') . '?' . http_build_query($params);
}

function cc_plain_to_html($text){
    $text = trim((string)$text);
    if($text === '') return '';
    if(preg_match('/<\s*(p|h2|h3|ul|ol|blockquote|img|div|br)\b/i', $text)) return $text;
    $parts = preg_split("/\n{2,}/", str_replace("\r\n", "\n", $text));
    $html = array();
    foreach($parts as $part){
        $part = trim($part);
        if($part === '') continue;
        $html[] = '<p>' . nl2br(admin_h($part)) . '</p>';
    }
    return implode("\n", $html);
}

function cc_parse_batch_block($block){
    $block = trim((string)$block);
    if($block === '') return null;
    $lines = preg_split("/\r\n|\r|\n/", $block);
    $fields = array('title'=>'','summary'=>'','image'=>'','type'=>'','content'=>'');
    $map = array(
        '标题'=>'title','title'=>'title',
        '摘要'=>'summary','summary'=>'summary','description'=>'summary',
        '图片'=>'image','封面图'=>'image','image'=>'image','cover'=>'image',
        '分类'=>'type','类型'=>'type','type'=>'type','category'=>'type',
        '正文'=>'content','内容'=>'content','content'=>'content','body'=>'content',
    );
    $current = '';
    $usedField = false;
    foreach($lines as $line){
        if(preg_match('/^\s*([^:：]{1,20})\s*[:：]\s*(.*)$/u', $line, $m)){
            $key = strtolower(trim($m[1]));
            $zhKey = trim($m[1]);
            $field = $map[$zhKey] ?? ($map[$key] ?? '');
            if($field){
                $current = $field;
                $fields[$current] = trim($m[2]);
                $usedField = true;
                continue;
            }
        }
        if($current){
            $fields[$current] .= ($fields[$current] === '' ? '' : "\n") . $line;
        }
    }
    if(!$usedField){
        $title = trim(array_shift($lines));
        $content = trim(implode("\n", $lines));
        $fields['title'] = $title;
        $fields['content'] = $content;
    }
    $fields['title'] = trim($fields['title']);
    $fields['content'] = trim($fields['content']);
    if($fields['title'] === '' || $fields['content'] === '') return null;
    return $fields;
}

function cc_parse_batch_articles($raw){
    $raw = trim((string)$raw);
    if($raw === '') return array();
    $blocks = preg_split('/^\s*-{3,}\s*$/m', $raw);
    $items = array();
    foreach($blocks as $block){
        $item = cc_parse_batch_block($block);
        if($item) $items[] = $item;
    }
    return $items;
}

function cc_title_from_txt_filename($name){
    $name = preg_replace('/\.[^.]+$/', '', basename((string)$name));
    $name = str_replace(array('_','-'), ' ', $name);
    $name = trim(preg_replace('/\s+/u', ' ', $name));
    return $name;
}

function cc_parse_txt_import_file($tmp, $name){
    if(!is_file($tmp)) return null;
    $raw = file_get_contents($tmp);
    if($raw === false) return null;
    $raw = preg_replace('/^\xEF\xBB\xBF/', '', $raw);
    $item = cc_parse_batch_block($raw);
    if(!$item){
        $item = array('title'=>'', 'summary'=>'', 'image'=>'', 'type'=>'', 'content'=>trim($raw));
    }
    $item['title'] = cc_title_from_txt_filename($name);
    if($item['title'] === '' || trim($item['content']) === '') return null;
    return $item;
}

function cc_parse_txt_import_uploads($files){
    $items = array();
    if(empty($files) || empty($files['name']) || !is_array($files['name'])) return $items;
    $total = count($files['name']);
    for($i=0; $i<$total; $i++){
        if(($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) continue;
        if(($files['error'][$i] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) continue;
        $name = (string)($files['name'][$i] ?? '');
        if(strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== 'txt') continue;
        if(($files['size'][$i] ?? 0) > 1024 * 1024) continue;
        $item = cc_parse_txt_import_file($files['tmp_name'][$i] ?? '', $name);
        if($item) $items[] = $item;
    }
    return $items;
}

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $action = $_POST['action'] ?? 'save_content';
    $currentTab = $action === 'batch_import_content' ? 'import' : 'manage';

    if($action === 'batch_import_content'){
        $scope = $_POST['batch_scope'] ?? 'site';
        if(!in_array($scope, array('site','theme','global'), true)) $scope = 'site';
        $target = $scope === 'global' ? 'all' : ($scope === 'theme' ? ($_POST['batch_theme'] ?? $currentTheme) : ($_POST['batch_site'] ?? $host));
        $channel = $_POST['batch_channel'] ?? 'news';
        if(!isset($channels[$channel])) $channel = 'news';
        $status = $_POST['batch_status'] ?? 'pending';
        if(!in_array($status, array('draft','pending'), true)) $status = 'pending';
        $publishStart = content_center_format_publish_time($_POST['batch_publish_time'] ?? '') ?: date('Y-m-d H:i:s');
        $publishStartTs = strtotime($publishStart) ?: time();
        $intervalMinutes = max(0, min(1440, intval($_POST['batch_interval_minutes'] ?? 10)));
        $items = cc_parse_txt_import_uploads($_FILES['batch_files'] ?? array());
        $maxImport = 200;
        if(count($items) > $maxImport) $items = array_slice($items, 0, $maxImport);
        $okCount = 0;
        foreach($items as $idx=>$item){
            $publishTime = date('Y-m-d H:i:s', $publishStartTs + ($idx * $intervalMinutes * 60));
            $article = array(
                'article_id' => 'CNT' . date('YmdHis') . mt_rand(100,999) . sprintf('%03d', $idx + 1),
                'title' => $item['title'],
                'summary' => trim($item['summary']) !== '' ? trim($item['summary']) : (function_exists('mb_substr') ? mb_substr(strip_tags($item['content']), 0, 90, 'UTF-8') : substr(strip_tags($item['content']), 0, 180)),
                'content' => cc_plain_to_html($item['content']),
                'content_format' => 'html',
                'image' => trim($item['image']),
                'type' => trim($item['type'] !== '' ? $item['type'] : ($channel === 'product' ? '产品服务' : ($channel === 'case' ? '客户案例' : ($channel === 'faq' ? '常见问题' : '企业新闻')))),
                'status' => $status,
                'publish_time' => $publishTime,
                'delay_publish' => $intervalMinutes > 0,
            );
            if(content_center_save_article($article, $scope, $target, $channel, '')) $okCount++;
        }
        if($okCount > 0){
            $msg = '批量导入完成：成功导入 ' . intval($okCount) . ' 篇内容，已按间隔时间生成发布时间。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_batch_import', $scope . '/' . $target . '/' . $channel . '/' . $okCount);
        }else{
            $error = '批量导入失败：未识别到有效 TXT 文章。请检查是否选择了 .txt 文件，且正文内容不为空。';
        }
    }

    if($action === 'restore_content'){
        $trashFile = base64_decode((string)($_POST['trash_file'] ?? ''), true);
        if($trashFile && content_center_restore_article($trashFile)){
            $msg = '内容已从回收站恢复。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_restore', basename($trashFile));
        }else{
            $error = '恢复失败：回收站文件不存在或无权限。';
        }
    }

    if($action === 'purge_content'){
        $trashFile = base64_decode((string)($_POST['trash_file'] ?? ''), true);
        if($trashFile && content_center_purge_trash_file($trashFile)){
            $msg = '回收站内容已永久删除。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_purge', basename($trashFile));
        }else{
            $error = '永久删除失败：回收站文件不存在或无权限。';
        }
    }

    if($action === 'batch_purge_content'){
        $trashFiles = $_POST['trash_files'] ?? array();
        if(!is_array($trashFiles)) $trashFiles = array();
        $trashFiles = array_values(array_unique(array_filter(array_map('trim', $trashFiles))));
        $okCount = 0;
        foreach($trashFiles as $encoded){
            $trashFile = base64_decode($encoded, true);
            if($trashFile && content_center_purge_trash_file($trashFile)) $okCount++;
        }
        if($okCount > 0){
            $msg = '回收站批量删除完成：已永久删除 ' . intval($okCount) . ' 条内容。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_batch_purge', (string)$okCount);
        }else{
            $error = '回收站批量删除失败：请先勾选需要永久删除的内容。';
        }
    }

    if($action === 'clear_trash_content'){
        $okCount = 0;
        foreach(content_center_trash_files() as $trashFile){
            if(content_center_purge_trash_file($trashFile)) $okCount++;
        }
        if($okCount > 0){
            $msg = '回收站已清空：已永久删除 ' . intval($okCount) . ' 条内容。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_clear_trash', (string)$okCount);
        }else{
            $error = '回收站暂无可清空内容。';
        }
    }

    if($action === 'delete_content'){
        $articleId = trim($_POST['article_id'] ?? '');
        if($articleId === ''){
            $error = '缺少内容 ID。';
        }elseif(content_center_delete_article($articleId)){
            $msg = '内容已移入回收站。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_delete', $articleId);
        }else{
            $error = '删除失败：内容不存在或文件无权限。';
        }
    }

    if($action === 'batch_delete_content'){
        $ids = $_POST['article_ids'] ?? array();
        if(!is_array($ids)) $ids = array();
        $ids = array_values(array_unique(array_filter(array_map('trim', $ids))));
        $okCount = 0;
        foreach($ids as $id){
            if($id !== '' && content_center_delete_article($id)) $okCount++;
        }
        if($okCount > 0){
            $msg = '批量删除完成：已移入回收站 ' . intval($okCount) . ' 篇内容。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_batch_delete', implode(',', $ids));
        }else{
            $error = '批量删除失败：请先勾选需要删除的内容。';
        }
    }

    if($action === 'clear_content_list'){
        $filters = array(
            'q' => trim((string)($_POST['clear_q'] ?? '')),
            'channel' => trim((string)($_POST['clear_channel'] ?? '')),
            'status' => trim((string)($_POST['clear_status'] ?? '')),
            'scope' => trim((string)($_POST['clear_scope'] ?? '')),
        );
        $recordsToDelete = content_center_admin_records($filters);
        $okCount = 0;
        foreach($recordsToDelete as $row){
            $id = trim((string)($row['article_id'] ?? ''));
            if($id !== '' && content_center_delete_article($id)) $okCount++;
        }
        if($okCount > 0){
            $msg = '当前筛选内容已清空：已移入回收站 ' . intval($okCount) . ' 篇内容。';
            if(function_exists('admin_oplog')) admin_oplog('content_center_clear_list', 'count=' . $okCount);
        }else{
            $error = '当前筛选下没有可清空的内容。';
        }
    }

    if($action === 'save_content'){
        $articleId = trim($_POST['article_id'] ?? '');
        $oldFile = $articleId !== '' ? content_center_find_file($articleId) : '';
        $oldArticle = $oldFile ? content_center_read_raw($oldFile) : array();
        if(!is_array($oldArticle)) $oldArticle = array();

        $scope = $_POST['scope'] ?? 'site';
        if(!in_array($scope, array('site','theme','global'), true)) $scope = 'site';
        $target = $scope === 'global' ? 'all' : ($scope === 'theme' ? ($_POST['theme'] ?? $currentTheme) : ($_POST['site'] ?? $host));
        $lastPostScope = $scope;
        $lastPostTarget = $target;
        $publishMode = $_POST['publish_mode'] ?? 'now';
        $lastPostPublishMode = $publishMode;
        $publishTime = date('Y-m-d H:i:s');
        if($publishMode === 'schedule'){
            $publishTime = content_center_format_publish_time($_POST['publish_time'] ?? '');
            if($publishTime === '') $error = '请选择有效的发布时间。';
        }

        $channel = $_POST['channel'] ?? 'news';
        if(!isset($channels[$channel])) $channel = 'news';
        $lastPostChannel = $channel;
        $status = cc_article_status($publishMode, $_POST['status'] ?? '');
        $lastPostStatus = $status;
        if($status === 'pending' && $publishMode !== 'schedule') $publishMode = 'schedule';
        if($status === 'draft') $publishTime = content_center_format_publish_time($_POST['publish_time'] ?? '') ?: date('Y-m-d H:i:s');

        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');
        $image = trim($_POST['image'] ?? '');
        $coverUpload = cc_upload_image_file($_FILES['image_file'] ?? array());
        if(!empty($coverUpload['ok'])){
            $image = $coverUpload['url'];
        }elseif(empty($coverUpload['empty']) && !empty($coverUpload['error'])){
            $error = $coverUpload['error'];
        }
        $article = array_merge($oldArticle, array(
            'article_id' => $articleId !== '' ? $articleId : ('CNT' . date('YmdHis') . mt_rand(100,999)),
            'title' => $title,
            'summary' => trim($_POST['summary'] ?? ''),
            'content' => $content,
            'content_format' => 'html',
            'image' => $image,
            'type' => trim($_POST['type'] ?? ($channel === 'product' ? '产品服务' : ($channel === 'case' ? '客户案例' : ($channel === 'faq' ? '常见问题' : '企业新闻')))),
            'status' => $status,
            'publish_time' => $publishTime,
            'delay_publish' => !empty($_POST['delay_publish']),
        ));
        $lastPostArticle = $article;

        if($title === '' || $content === ''){
            $error = '标题和正文不能为空。';
        }elseif($error === ''){
            $ok = content_center_save_article($article, $scope, $target, $channel, $oldFile);
            $msg = $ok ? ($oldFile ? '内容已更新。' : '内容已保存。') : '保存失败，请检查 data/content_center 目录权限。';
            if($ok && function_exists('admin_oplog')) admin_oplog($oldFile ? 'content_center_update' : 'content_center_save', $scope . '/' . $target . '/' . $channel . '/' . $article['title']);
        }
    }
}

$editId = trim($_GET['edit'] ?? '');
$editFile = $editId !== '' ? content_center_find_file($editId) : '';
$editArticle = $editFile ? content_center_read_raw($editFile) : array();
if(!is_array($editArticle)) $editArticle = array();
$isEdit = !empty($editArticle);

$baseFormArticle = array(
    'article_id'=>'',
    'title'=>'',
    'summary'=>'',
    'content'=>'',
    'image'=>'',
    'type'=>'',
    'status'=>'published',
    'publish_time'=>date('Y-m-d H:i:s', time()+3600),
    'delay_publish'=>0,
    'scope'=>'site',
    'target'=>$host,
    'channel'=>'news',
);

if($isEdit){
    $formArticle = array_merge($baseFormArticle, $editArticle);
}elseif($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_content' && $lastPostArticle){
    $formArticle = array_merge($baseFormArticle, $lastPostArticle);
    $formArticle['article_id'] = '';
    $formArticle['title'] = '';
    $formArticle['summary'] = '';
    $formArticle['content'] = '';
    $formArticle['scope'] = $lastPostScope ?: ($formArticle['scope'] ?? 'site');
    $formArticle['target'] = $lastPostTarget ?: ($formArticle['target'] ?? $host);
    $formArticle['channel'] = $lastPostChannel ?: ($formArticle['channel'] ?? 'news');
    $formArticle['status'] = $lastPostStatus ?: ($formArticle['status'] ?? 'published');
}else{
    $formArticle = $baseFormArticle;
}

$currentTab = $currentTab ?? ($_GET['tab'] ?? 'manage');
if(!in_array($currentTab, array('manage','import'), true)) $currentTab = 'manage';

$formScope = $formArticle['scope'] ?? 'site';
$formChannel = $formArticle['channel'] ?? 'news';
$formTarget = $formArticle['target'] ?? ($formScope === 'theme' ? $currentTheme : $host);
$formStatus = $formArticle['status'] ?? 'published';
$formPublishMode = ($lastPostPublishMode ?: ($formStatus === 'pending' ? 'schedule' : 'now'));

$q = trim($_GET['q'] ?? '');
$filterChannel = trim($_GET['channel'] ?? '');
$filterStatus = trim($_GET['status'] ?? '');
$filterScope = trim($_GET['scope'] ?? '');
if(function_exists('content_center_publish_due_articles')) content_center_publish_due_articles();
$records = content_center_admin_records(array('q'=>$q,'channel'=>$filterChannel,'status'=>$filterStatus,'scope'=>$filterScope));
$allRecords = content_center_admin_records(array());
$contentStats = cc_content_stats($allRecords, $channels, $scopes);
$overview = array('total'=>count($allRecords), 'published'=>0, 'pending'=>0, 'draft'=>0, 'trash'=>0);
foreach($allRecords as $row){
    $status = $row['status'] ?? 'published';
    if(isset($overview[$status])) $overview[$status]++;
}
$recordPageSize = intval($_GET['page_size'] ?? 20);
$recordPage = intval($_GET['page'] ?? 1);
list($pageRecords, $recordTotal, $recordPages, $recordPage, $recordPageSize) = cc_paginate_items($records, $recordPage, $recordPageSize);
$trashRecords = array();
foreach(content_center_trash_files() as $trashFile){
    $trashArticle = content_center_read_raw($trashFile);
    if($trashArticle){
        $trashArticle['trash_file'] = $trashFile;
        $trashArticle['trash_time'] = date('Y-m-d H:i:s', filemtime($trashFile));
        $trashRecords[] = $trashArticle;
    }
}
$overview['trash'] = count($trashRecords);
usort($trashRecords, function($a, $b){
    return strtotime($b['trash_time'] ?? '') <=> strtotime($a['trash_time'] ?? '');
});
$trashPageSize = intval($_GET['trash_page_size'] ?? 20);
$trashPage = intval($_GET['trash_page'] ?? 1);
list($pageTrashRecords, $trashTotal, $trashPages, $trashPage, $trashPageSize) = cc_paginate_items($trashRecords, $trashPage, $trashPageSize);

admin_header('内容中心');
?>
<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>
<?php if($error): ?><div class="error"><?php echo admin_h($error); ?></div><?php endif; ?>

<div class="cc-subnav">
    <a class="<?php echo $currentTab === 'manage' ? 'active' : ''; ?>" href="<?php echo admin_h(cms_admin_url('content_center.php')); ?>">内容管理</a>
    <a class="<?php echo $currentTab === 'import' ? 'active' : ''; ?>" href="<?php echo admin_h(cms_admin_url('content_center.php') . '?tab=import'); ?>">批量导入 TXT</a>
</div>

<?php if($currentTab === 'manage'): ?>
<div class="cc-dashboard">
    <div><span>全部内容</span><strong><?php echo intval($overview['total']); ?></strong></div>
    <div><span>已发布</span><strong><?php echo intval($overview['published']); ?></strong></div>
    <div><span>待发布</span><strong><?php echo intval($overview['pending']); ?></strong></div>
    <div><span>草稿</span><strong><?php echo intval($overview['draft']); ?></strong></div>
    <div><span>回收站</span><strong><?php echo intval($overview['trash']); ?></strong></div>
</div>

<div class="card cc-stats-card cc-stats-card-top">
<h2>内容统计</h2>
<table><tr><th>范围</th><th>目标</th><th>栏目</th><th>总数</th><th>草稿</th><th>待发布</th><th>已发布</th></tr>
<?php if(!$contentStats): ?>
<tr><td colspan="7">暂无内容统计</td></tr>
<?php endif; ?>
<?php foreach($contentStats as $stat): ?>
<tr>
<td><?php echo admin_h($stat['scope_label']); ?></td>
<td><?php echo admin_h($stat['scope'] === 'theme' ? admin_site_theme_label($stat['target'], true) : $stat['target']); ?></td>
<td><?php echo admin_h($channels[$stat['channel']] ?? $stat['channel']); ?></td>
<td><?php echo intval($stat['total']); ?></td>
<td><?php echo intval($stat['draft']); ?></td>
<td><?php echo intval($stat['pending']); ?></td>
<td><?php echo intval($stat['published']); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<div class="card cc-compose-card">
<h2><?php echo $isEdit ? '编辑内容：' . admin_h($formArticle['title'] ?? '') : '新增内容'; ?></h2>
<p class="help">内容中心支持新增、编辑、删除、草稿、定时发布和回收站。保存文件名会自动包含内容 ID 与标题，便于后期人工识别。</p>
<form method="post" class="config-form content-center-form" enctype="multipart/form-data">
<input type="hidden" name="action" value="save_content">
<input type="hidden" name="article_id" value="<?php echo admin_h($formArticle['article_id'] ?? ''); ?>">

<aside class="cc-compose-side">
<div class="form-section cc-form-section">
<h3>发布范围</h3>
<div class="cc-choice-row" role="radiogroup" aria-label="发布范围">
<label class="cc-choice-card"><input type="radio" name="scope" value="site" <?php echo $formScope==='site'?'checked':''; ?>><span>当前站点</span></label>
<label class="cc-choice-card"><input type="radio" name="scope" value="theme" <?php echo $formScope==='theme'?'checked':''; ?>><span>当前主题</span></label>
<label class="cc-choice-card"><input type="radio" name="scope" value="global" <?php echo $formScope==='global'?'checked':''; ?>><span>全部主题</span></label>
</div>
<div class="form-grid cc-target-grid">
<label class="cc-target cc-target-theme">目标主题
<select name="theme"><?php foreach($themeMap as $t=>$themeName): ?><option value="<?php echo admin_h($t); ?>" <?php echo ($formScope==='theme' && $formTarget===$t) || ($formScope!=='theme' && $t===$currentTheme)?'selected':''; ?>><?php echo admin_h($themeName . ' / ' . $t); ?></option><?php endforeach; ?></select></label>
<label class="cc-target cc-target-site">站点域名
<select name="site"><?php foreach($domains as $d=>$cfg): ?><option value="<?php echo admin_h($d); ?>" <?php echo ($formScope==='site' && $formTarget===$d) || ($formScope!=='site' && $d===$host)?'selected':''; ?>><?php echo admin_h($d); ?></option><?php endforeach; ?></select></label>
</div>
</div>

<div class="form-section cc-form-section">
<h3>发布设置</h3>
<div class="form-grid">
<label>发布栏目
<select name="channel">
<?php foreach($channels as $key=>$name): ?><option value="<?php echo admin_h($key); ?>" <?php echo $formChannel===$key?'selected':''; ?>><?php echo admin_h($name); ?></option><?php endforeach; ?>
</select>
</label>
<label>内容状态
<select name="status">
<?php foreach($statuses as $key=>$name): ?><option value="<?php echo admin_h($key); ?>" <?php echo $formStatus===$key?'selected':''; ?>><?php echo admin_h($name); ?></option><?php endforeach; ?>
</select>
</label>
</div>
<div class="cc-choice-row cc-choice-row-small" role="radiogroup" aria-label="发布方式">
<label class="cc-choice-card"><input type="radio" name="publish_mode" value="now" <?php echo $formPublishMode==='now'?'checked':''; ?>><span>立即发布</span></label>
<label class="cc-choice-card"><input type="radio" name="publish_mode" value="schedule" <?php echo $formPublishMode==='schedule'?'checked':''; ?>><span>定时发布</span></label>
</div>
<div class="form-grid cc-schedule-grid">
<label class="cc-schedule-field">选择发布时间
<input type="datetime-local" name="publish_time" step="1" value="<?php echo admin_h(cc_datetime_local_value($formArticle['publish_time'] ?? '')); ?>"></label>
<label class="cc-checkline"><input type="checkbox" name="delay_publish" value="1" <?php echo !empty($formArticle['delay_publish'])?'checked':''; ?>><span>启用随机延迟发布</span></label>
</div>
</div>
</aside>

<div class="cc-compose-main">
<div class="form-grid two">
<label>标题<input name="title" value="<?php echo admin_h($formArticle['title'] ?? ''); ?>" placeholder="请输入标题"></label>
<label>分类/类型<input name="type" value="<?php echo admin_h($formArticle['type'] ?? ''); ?>" placeholder="例如：企业新闻 / 产品服务 / 客户案例"></label>
</div>
<label>摘要<textarea name="summary" rows="3" class="small-textarea" placeholder="文章摘要"><?php echo admin_h($formArticle['summary'] ?? ''); ?></textarea></label>
<div class="cc-image-upload">
<label>封面图
    <div class="cc-image-control">
        <input name="image" value="<?php echo admin_h($formArticle['image'] ?? ''); ?>" placeholder="封面图地址，可粘贴 URL，也可点击右侧上传">
        <button type="button" data-cover-upload>上传</button>
    </div>
    <input type="file" name="image_file" accept="image/jpeg,image/png,image/webp,image/gif" hidden>
</label>
<div class="cc-image-preview" <?php echo empty($formArticle['image']) ? 'hidden' : ''; ?>><img src="<?php echo admin_h($formArticle['image'] ?? ''); ?>" alt=""></div>
</div>

<label>正文编辑器</label>
<div class="cc-editor" data-editor>
    <div class="cc-editor-toolbar">
        <button type="button" data-command="formatBlock" data-value="h2">H2</button>
        <button type="button" data-command="formatBlock" data-value="h3">H3</button>
        <button type="button" data-command="formatBlock" data-value="p">段落</button>
        <button type="button" data-command="justifyLeft">左对齐</button>
        <button type="button" data-command="justifyCenter">居中</button>
        <button type="button" data-command="justifyRight">右对齐</button>
        <select class="cc-editor-select" data-line-height>
            <option value="">行距</option>
            <option value="1.5">1.5</option>
            <option value="1.8">1.8</option>
            <option value="2">2.0</option>
            <option value="2.4">2.4</option>
        </select>
        <button type="button" data-command="bold"><strong>B</strong></button>
        <button type="button" data-command="italic"><em>I</em></button>
        <button type="button" data-command="insertUnorderedList">列表</button>
        <button type="button" data-command="insertOrderedList">编号</button>
        <button type="button" data-blockquote>引用</button>
        <button type="button" data-link>链接</button>
        <button type="button" data-image>图片</button>
        <button type="button" data-image-center>图片居中</button>
        <select class="cc-editor-select" data-image-size>
            <option value="">图片大小</option>
            <option value="320">小图 320px</option>
            <option value="520">中图 520px</option>
            <option value="760">大图 760px</option>
            <option value="100%">通栏 100%</option>
        </select>
        <div class="cc-editor-image-panel" data-image-panel hidden>
            <input type="text" data-image-url placeholder="粘贴图片 URL">
            <button type="button" data-image-url-insert>插入</button>
            <button type="button" data-image-local>上传</button>
        </div>
        <button type="button" data-mode="source">源码</button>
        <button type="button" data-preview>预览</button>
        <input type="file" data-upload-input accept="image/jpeg,image/png,image/webp,image/gif" hidden>
    </div>
    <div class="cc-editor-workspace">
        <div class="cc-editor-canvas" contenteditable="true" data-placeholder="在这里直接编辑正文，可粘贴文字，也可用工具栏排版。"><?php echo function_exists('content_center_safe_html') ? content_center_safe_html($formArticle['content'] ?? '') : strip_tags((string)($formArticle['content'] ?? ''), '<p><br><strong><b><em><i><u><h2><h3><h4><ul><ol><li><blockquote><a><img><div><span>'); ?></div>
        <textarea name="content" rows="16" hidden><?php echo admin_h($formArticle['content'] ?? ''); ?></textarea>
        <div class="cc-editor-preview" hidden></div>
    </div>
</div>
<p><button><?php echo $isEdit ? '保存修改' : '保存内容'; ?></button> <?php if($isEdit): ?><a class="btn ghost" href="<?php echo admin_h(cms_admin_url('content_center.php')); ?>">取消编辑</a><?php endif; ?></p>
</div>
</form>
</div>

<?php endif; ?>
<?php if($currentTab === 'import'): ?>
<div class="card cc-import-card">
<h2>批量导入 TXT 文章</h2>
<p class="help">支持一次上传多个 <code>.txt</code> 文件，文件名作为文章标题。TXT 内容可按格式填写：摘要、图片、分类、正文；未写字段时整篇文本作为正文。导入状态限定为草稿或待发布，系统会按起始时间和间隔自动生成发布时间。</p>
<form method="post" action="<?php echo admin_h(cms_admin_url('content_center.php') . '?tab=import'); ?>" class="config-form cc-batch-import-form" enctype="multipart/form-data">
<input type="hidden" name="action" value="batch_import_content">
<div class="form-grid">
<label>导入栏目
<select name="batch_channel">
<?php foreach($channels as $key=>$name): ?><option value="<?php echo admin_h($key); ?>"><?php echo admin_h($name); ?></option><?php endforeach; ?>
</select>
</label>
<label>内容状态
<select name="batch_status">
<?php foreach(array('pending'=>'待发布','draft'=>'草稿') as $key=>$name): ?><option value="<?php echo admin_h($key); ?>" <?php echo $key === 'pending' ? 'selected' : ''; ?>><?php echo admin_h($name); ?></option><?php endforeach; ?>
</select>
</label>
<label>起始发布时间
<input type="datetime-local" name="batch_publish_time" step="1" value="<?php echo admin_h(date('Y-m-d\TH:i:s', time() + 3600)); ?>">
</label>
<label>每篇间隔分钟
<input type="number" name="batch_interval_minutes" min="0" max="1440" value="10">
</label>
</div>
<div class="cc-choice-row cc-choice-row-small" role="radiogroup" aria-label="批量导入范围">
<label class="cc-choice-card"><input type="radio" name="batch_scope" value="site" checked><span>当前站点</span></label>
<label class="cc-choice-card"><input type="radio" name="batch_scope" value="theme"><span>当前主题</span></label>
<label class="cc-choice-card"><input type="radio" name="batch_scope" value="global"><span>全部主题</span></label>
</div>
<div class="form-grid">
<label class="cc-batch-target cc-batch-target-theme">目标主题
<select name="batch_theme"><?php foreach($themeMap as $t=>$themeName): ?><option value="<?php echo admin_h($t); ?>" <?php echo $t===$currentTheme?'selected':''; ?>><?php echo admin_h($themeName . ' / ' . $t); ?></option><?php endforeach; ?></select>
</label>
<label class="cc-batch-target cc-batch-target-site">站点域名
<select name="batch_site"><?php foreach($domains as $d=>$cfg): ?><option value="<?php echo admin_h($d); ?>" <?php echo $d===$host?'selected':''; ?>><?php echo admin_h($d); ?></option><?php endforeach; ?></select>
</label>
</div>
<label>选择 TXT 文件
<input type="file" name="batch_files[]" accept=".txt,text/plain" multiple>
</label>
<p><button>开始批量导入</button></p>
</form>
</div>
<?php endif; ?>

<?php if($currentTab === 'manage'): ?>
<div class="cc-ops-grid">
<div class="card cc-records-card">
<h2>内容记录</h2>
<form method="get" class="config-form search-bar">
<div class="form-grid">
<label>关键词搜索<input name="q" value="<?php echo admin_h($q); ?>" placeholder="标题 / 文件名 / 内容 ID / 目标"></label>
<label>栏目
<select name="channel"><option value="">全部栏目</option><?php foreach($channels as $k=>$v): ?><option value="<?php echo admin_h($k); ?>" <?php echo $filterChannel===$k?'selected':''; ?>><?php echo admin_h($v); ?></option><?php endforeach; ?></select>
</label>
<label>状态
<select name="status"><option value="">全部状态</option><?php foreach($statuses as $k=>$v): ?><option value="<?php echo admin_h($k); ?>" <?php echo $filterStatus===$k?'selected':''; ?>><?php echo admin_h($v); ?></option><?php endforeach; ?></select>
</label>
<label>范围
<select name="scope"><option value="">全部范围</option><?php foreach($scopes as $k=>$v): ?><option value="<?php echo admin_h($k); ?>" <?php echo $filterScope===$k?'selected':''; ?>><?php echo admin_h($v); ?></option><?php endforeach; ?></select>
</label>
</div>
<p><button>筛选</button> <a class="btn ghost" href="<?php echo admin_h(cms_admin_url('content_center.php')); ?>">重置</a></p>
</form>
<div class="cc-table-toolbar">
    <form method="post" id="cc-batch-delete-form">
    <input type="hidden" name="action" value="batch_delete_content">
    </form>
    <form method="post" id="cc-clear-list-form" data-confirm="确定清空当前筛选下的内容吗？清空后会进入回收站。">
    <input type="hidden" name="action" value="clear_content_list">
    <input type="hidden" name="clear_q" value="<?php echo admin_h($q); ?>">
    <input type="hidden" name="clear_channel" value="<?php echo admin_h($filterChannel); ?>">
    <input type="hidden" name="clear_status" value="<?php echo admin_h($filterStatus); ?>">
    <input type="hidden" name="clear_scope" value="<?php echo admin_h($filterScope); ?>">
    </form>
    <div class="cc-batch-actions">
    <button class="btn small danger" type="submit" form="cc-batch-delete-form">批量删除选中</button>
    <button class="btn small danger ghost" type="submit" form="cc-clear-list-form">清空当前列表</button>
    <span>共 <?php echo intval($recordTotal); ?> 条，第 <?php echo intval($recordPage); ?>/<?php echo intval($recordPages); ?> 页</span>
    </div>
    <form method="get" class="cc-page-size-form">
    <input type="hidden" name="q" value="<?php echo admin_h($q); ?>">
    <input type="hidden" name="channel" value="<?php echo admin_h($filterChannel); ?>">
    <input type="hidden" name="status" value="<?php echo admin_h($filterStatus); ?>">
    <input type="hidden" name="scope" value="<?php echo admin_h($filterScope); ?>">
    <input type="hidden" name="page" value="1">
    <label>每页
    <select name="page_size" onchange="this.form.submit()">
    <?php foreach(array(10,20,50,100) as $size): ?><option value="<?php echo intval($size); ?>" <?php echo $recordPageSize===$size?'selected':''; ?>><?php echo intval($size); ?> 条</option><?php endforeach; ?>
    </select>
    </label>
    </form>
</div>
<table class="content-record-table">
<tr><th><input type="checkbox" data-check-all></th><th>标题</th><th>文件名</th><th>栏目</th><th>范围</th><th>目标</th><th>状态</th><th>发布时间</th><th>操作</th></tr>
<?php if(!$pageRecords): ?>
<tr><td colspan="9">暂无内容记录</td></tr>
<?php endif; ?>
<?php foreach($pageRecords as $row): ?>
<tr>
<td><input type="checkbox" form="cc-batch-delete-form" name="article_ids[]" value="<?php echo admin_h($row['article_id'] ?? ''); ?>"></td>
<td><strong><?php echo admin_h($row['title'] ?? ''); ?></strong><br><span class="muted">ID：<?php echo admin_h($row['article_id'] ?? ''); ?></span></td>
<td><code><?php echo admin_h($row['filename'] ?? ''); ?></code></td>
<td><?php echo admin_h($channels[$row['channel'] ?? 'news'] ?? ($row['channel'] ?? '')); ?></td>
<td><?php echo admin_h($scopes[$row['scope'] ?? 'site'] ?? ($row['scope'] ?? '')); ?></td>
<td><?php echo admin_h(($row['scope'] ?? '') === 'theme' ? admin_site_theme_label($row['target'] ?? '', true) : ($row['target'] ?? '')); ?></td>
<td><?php echo admin_h($statuses[$row['status'] ?? 'published'] ?? ($row['status'] ?? '')); ?></td>
<td><?php echo admin_h($row['publish_time'] ?? ''); ?></td>
<td class="actions-cell"><div class="row-actions">
<a class="btn small" href="<?php echo admin_h(cms_admin_url('content_center.php') . '?edit=' . urlencode($row['article_id'] ?? '')); ?>">编辑</a>
<form method="post" data-confirm="确定删除这篇内容吗？删除后会进入回收站。"><input type="hidden" name="action" value="delete_content"><input type="hidden" name="article_id" value="<?php echo admin_h($row['article_id'] ?? ''); ?>"><button class="btn small danger" type="submit">删除</button></form>
</div></td>
</tr>
<?php endforeach; ?>
</table>
<?php if($recordPages > 1): ?>
<div class="pager cc-pager">
    <?php if($recordPage > 1): ?><a class="btn small ghost" href="<?php echo admin_h(cc_page_url($recordPage - 1)); ?>">上一页</a><?php endif; ?>
    <span>第 <?php echo intval($recordPage); ?> / <?php echo intval($recordPages); ?> 页</span>
    <?php if($recordPage < $recordPages): ?><a class="btn small ghost" href="<?php echo admin_h(cc_page_url($recordPage + 1)); ?>">下一页</a><?php endif; ?>
</div>
<?php endif; ?>
</div>

<div class="card cc-trash-card">
<h2>内容回收站</h2>
<p class="help">删除内容会先进入回收站，可恢复；确认不需要后再永久删除。</p>
<div class="cc-table-toolbar">
    <form method="post" id="cc-trash-batch-purge-form" data-confirm="确定永久删除选中的回收站内容吗？此操作不可恢复。">
    <input type="hidden" name="action" value="batch_purge_content">
    </form>
    <form method="post" id="cc-trash-clear-form" data-confirm="确定清空整个内容回收站吗？此操作不可恢复。">
    <input type="hidden" name="action" value="clear_trash_content">
    </form>
    <div class="cc-batch-actions">
    <button class="btn small danger" type="submit" form="cc-trash-batch-purge-form">批量永久删除</button>
    <button class="btn small danger ghost" type="submit" form="cc-trash-clear-form">清空回收站</button>
    <span>共 <?php echo intval($trashTotal); ?> 条，第 <?php echo intval($trashPage); ?>/<?php echo intval($trashPages); ?> 页</span>
    </div>
    <form method="get" class="cc-page-size-form">
    <input type="hidden" name="trash_page" value="1">
    <label>每页
    <select name="trash_page_size" onchange="this.form.submit()">
    <?php foreach(array(10,20,50,100) as $size): ?><option value="<?php echo intval($size); ?>" <?php echo $trashPageSize===$size?'selected':''; ?>><?php echo intval($size); ?> 条</option><?php endforeach; ?>
    </select>
    </label>
    </form>
</div>
<table class="content-record-table">
<tr><th><input type="checkbox" data-check-all="trash"></th><th>标题</th><th>栏目</th><th>范围</th><th>删除时间</th><th>操作</th></tr>
<?php if(!$pageTrashRecords): ?>
<tr><td colspan="6">暂无回收站内容</td></tr>
<?php endif; ?>
<?php foreach($pageTrashRecords as $row): ?>
<tr>
<td><input type="checkbox" form="cc-trash-batch-purge-form" name="trash_files[]" value="<?php echo admin_h(base64_encode($row['trash_file'])); ?>"></td>
<td><strong><?php echo admin_h($row['title'] ?? ''); ?></strong><br><span class="muted"><?php echo admin_h($row['filename'] ?? basename($row['trash_file'] ?? '')); ?></span></td>
<td><?php echo admin_h($channels[$row['channel'] ?? 'news'] ?? ($row['channel'] ?? '')); ?></td>
<td><?php echo admin_h(($scopes[$row['scope'] ?? 'site'] ?? ($row['scope'] ?? '')) . ' / ' . ($row['target'] ?? '')); ?></td>
<td><?php echo admin_h($row['trash_time'] ?? ''); ?></td>
<td class="actions-cell"><div class="row-actions">
<form method="post"><input type="hidden" name="action" value="restore_content"><input type="hidden" name="trash_file" value="<?php echo admin_h(base64_encode($row['trash_file'])); ?>"><button class="btn small" type="submit">恢复</button></form>
<form method="post" data-confirm="确定永久删除这条回收站内容吗？此操作不可恢复。"><input type="hidden" name="action" value="purge_content"><input type="hidden" name="trash_file" value="<?php echo admin_h(base64_encode($row['trash_file'])); ?>"><button class="btn small danger" type="submit">永久删除</button></form>
</div></td>
</tr>
<?php endforeach; ?>
</table>
<?php if($trashPages > 1): ?>
<div class="pager cc-pager">
    <?php if($trashPage > 1): ?><a class="btn small ghost" href="<?php echo admin_h(cc_page_url($trashPage - 1, 'trash_page')); ?>">上一页</a><?php endif; ?>
    <span>第 <?php echo intval($trashPage); ?> / <?php echo intval($trashPages); ?> 页</span>
    <?php if($trashPage < $trashPages): ?><a class="btn small ghost" href="<?php echo admin_h(cc_page_url($trashPage + 1, 'trash_page')); ?>">下一页</a><?php endif; ?>
</div>
<?php endif; ?>
</div>

</div>
<?php endif; ?>
<script>
(function(){
    var form = document.querySelector('.content-center-form');
    function setupBatchImport(){
        var batchForm = document.querySelector('.cc-batch-import-form');
        if(!batchForm) return;
        var batchScopeInputs = batchForm.querySelectorAll('input[name="batch_scope"]');
        var batchThemeWrap = batchForm.querySelector('.cc-batch-target-theme');
        var batchSiteWrap = batchForm.querySelector('.cc-batch-target-site');
        function batchCheckedScope(){ var el = batchForm.querySelector('input[name="batch_scope"]:checked'); return el ? el.value : 'site'; }
        function setBatchBlock(wrap, visible){ if(!wrap) return; wrap.style.display = visible ? '' : 'none'; wrap.querySelectorAll('input,select,textarea').forEach(function(field){ field.disabled = !visible; }); }
        function syncBatchScope(){ var scope = batchCheckedScope(); setBatchBlock(batchSiteWrap, scope === 'site'); setBatchBlock(batchThemeWrap, scope === 'theme'); }
        batchScopeInputs.forEach(function(el){ el.addEventListener('change', syncBatchScope); });
        syncBatchScope();
    }
    if(!form){
        setupBatchImport();
        return;
    }
    var scopeInputs = form.querySelectorAll('input[name="scope"]');
    var modeInputs = form.querySelectorAll('input[name="publish_mode"]');
    var statusSelect = form.querySelector('select[name="status"]');
    var themeWrap = form.querySelector('.cc-target-theme');
    var siteWrap = form.querySelector('.cc-target-site');
    var scheduleWrap = form.querySelector('.cc-schedule-field');
    var publishInput = form.querySelector('input[name="publish_time"]');
    function checkedValue(name){ var el = form.querySelector('input[name="'+name+'"]:checked'); return el ? el.value : ''; }
    function setBlock(wrap, visible){ if(!wrap) return; wrap.style.display = visible ? '' : 'none'; wrap.querySelectorAll('input,select,textarea').forEach(function(field){ field.disabled = !visible; }); }
    function syncScope(){ var scope = checkedValue('scope'); setBlock(siteWrap, scope === 'site'); setBlock(themeWrap, scope === 'theme'); }
    function syncPublish(){ var scheduled = checkedValue('publish_mode') === 'schedule' || (statusSelect && statusSelect.value === 'pending'); setBlock(scheduleWrap, scheduled); if(publishInput) publishInput.required = scheduled; }
    scopeInputs.forEach(function(el){ el.addEventListener('change', syncScope); });
    modeInputs.forEach(function(el){ el.addEventListener('change', syncPublish); });
    if(statusSelect){ statusSelect.addEventListener('change', function(){ if(this.value === 'pending'){ var sch=form.querySelector('input[name="publish_mode"][value="schedule"]'); if(sch) sch.checked=true; } syncPublish(); }); }
    syncScope(); syncPublish();

    setupBatchImport();

    document.querySelectorAll('[data-check-all]').forEach(function(checkAll){
        checkAll.addEventListener('change', function(){
            var targetName = checkAll.getAttribute('data-check-all') === 'trash' ? 'trash_files[]' : 'article_ids[]';
            document.querySelectorAll('input[name="'+targetName+'"]').forEach(function(box){
                box.checked = checkAll.checked;
            });
        });
    });

    var coverUploadBtn = form.querySelector('[data-cover-upload]');
    var coverFile = form.querySelector('input[name="image_file"]');
    var coverUrl = form.querySelector('input[name="image"]');
    var coverPreview = form.querySelector('.cc-image-preview');
    var coverPreviewImg = coverPreview ? coverPreview.querySelector('img') : null;
    if(coverUploadBtn && coverFile){
        coverUploadBtn.addEventListener('click', function(){ coverFile.click(); });
        coverFile.addEventListener('change', function(){
            var file = coverFile.files && coverFile.files[0];
            if(!file) return;
            if(coverPreviewImg && window.URL){
                coverPreviewImg.src = URL.createObjectURL(file);
                coverPreview.hidden = false;
            }
        });
    }
    if(coverUrl && coverPreviewImg){
        coverUrl.addEventListener('input', function(){
            var value = coverUrl.value.trim();
            if(value){
                coverPreviewImg.src = value;
                coverPreview.hidden = false;
            }else if(coverPreview){
                coverPreview.hidden = true;
            }
        });
    }

    var editor = document.querySelector('[data-editor]');
    if(editor){
        var textarea = editor.querySelector('textarea[name="content"]');
        var canvas = editor.querySelector('.cc-editor-canvas');
        var preview = editor.querySelector('.cc-editor-preview');
        var sourceMode = false;
        function syncToTextarea(){ textarea.value = sourceMode ? textarea.value : canvas.innerHTML.trim(); }
        function syncToCanvas(){ canvas.innerHTML = textarea.value; }
        function focusCanvas(){ canvas.focus(); }
        function exec(command, value){
            if(sourceMode) return;
            focusCanvas();
            document.execCommand(command, false, value || null);
            syncToTextarea();
        }
        function currentImageSize(){
            var select = editor.querySelector('[data-image-size]');
            return select ? select.value : '';
        }
        function imageStyleAttr(size){
            size = String(size || '').trim();
            var width = '';
            if(size === '100%') width = 'width:100%;';
            else if(/^\d+$/.test(size)) width = 'width:' + size + 'px;';
            return 'display:inline-block;max-width:100%;height:auto;' + width;
        }
        function centeredImageHtml(url, size){
            var safeUrl = String(url || '').replace(/"/g, '&quot;');
            return '<p style="text-align:center"><img src="' + safeUrl + '" alt="" style="' + imageStyleAttr(size) + '"></p>';
        }
        function insertHtml(html){
            if(sourceMode){
                textarea.value += html;
                return;
            }
            focusCanvas();
            document.execCommand('insertHTML', false, html);
            syncToTextarea();
        }
        function currentBlock(){
            var selection = window.getSelection();
            if(!selection || !selection.anchorNode) return null;
            var node = selection.anchorNode.nodeType === 1 ? selection.anchorNode : selection.anchorNode.parentElement;
            while(node && node !== canvas){
                if(/^(P|DIV|LI|H2|H3|H4|BLOCKQUOTE)$/i.test(node.tagName)) return node;
                node = node.parentElement;
            }
            return null;
        }
        function selectedImage(){
            var selection = window.getSelection();
            if(!selection || !selection.anchorNode) return null;
            var node = selection.anchorNode.nodeType === 1 ? selection.anchorNode : selection.anchorNode.parentElement;
            while(node && node !== canvas){
                if(node.tagName && node.tagName.toUpperCase() === 'IMG') return node;
                var img = node.querySelector ? node.querySelector('img') : null;
                if(img) return img;
                node = node.parentElement;
            }
            return null;
        }
        function selectedText(){
            var selection = window.getSelection();
            return selection && selection.toString() ? selection.toString() : '链接文字';
        }
        editor.querySelectorAll('[data-command]').forEach(function(btn){
            btn.addEventListener('click', function(){
                var command = this.getAttribute('data-command');
                var value = this.getAttribute('data-value') || null;
                exec(command, value);
            });
        });
        var lineHeightSelect = editor.querySelector('[data-line-height]');
        if(lineHeightSelect){
            lineHeightSelect.addEventListener('change', function(){
                if(!this.value || sourceMode) return;
                focusCanvas();
                var block = currentBlock();
                if(!block){
                    insertHtml('<p style="line-height:'+this.value+'"><br></p>');
                }else{
                    block.style.lineHeight = this.value;
                    syncToTextarea();
                }
                this.value = '';
            });
        }
        var imageSizeSelect = editor.querySelector('[data-image-size]');
        if(imageSizeSelect){
            imageSizeSelect.addEventListener('change', function(){
                if(sourceMode) return;
                var img = selectedImage();
                if(!img || !this.value) return;
                img.style.display = 'inline-block';
                img.style.maxWidth = '100%';
                img.style.height = 'auto';
                if(this.value === '100%'){
                    img.style.width = '100%';
                }else if(/^\d+$/.test(this.value)){
                    img.style.width = this.value + 'px';
                }
                var wrap = img.parentElement;
                if(wrap && wrap !== canvas) wrap.style.textAlign = 'center';
                syncToTextarea();
            });
        }
        var imageCenterBtn = editor.querySelector('[data-image-center]');
        if(imageCenterBtn){
            imageCenterBtn.addEventListener('click', function(){
                if(sourceMode) return;
                focusCanvas();
                var img = selectedImage();
                if(img){
                    var wrap = img.parentElement;
                    if(wrap && wrap !== canvas) wrap.style.textAlign = 'center';
                    img.style.display = 'inline-block';
                }else{
                    document.execCommand('justifyCenter', false, null);
                }
                syncToTextarea();
            });
        }
        var quoteBtn = editor.querySelector('[data-blockquote]');
        if(quoteBtn){ quoteBtn.addEventListener('click', function(){ insertHtml('<blockquote>引用内容</blockquote>'); }); }
        var linkBtn = editor.querySelector('[data-link]');
        if(linkBtn){ linkBtn.addEventListener('click', function(){
            var url = prompt('请输入链接地址', 'https://');
            if(!url) return;
            insertHtml('<a href="'+url.replace(/"/g, '&quot;')+'" target="_blank" rel="nofollow">'+selectedText()+'</a>');
        }); }
        var imageBtn = editor.querySelector('[data-image]');
        var imagePanel = editor.querySelector('[data-image-panel]');
        var imageUrlInput = editor.querySelector('[data-image-url]');
        var imageUrlInsert = editor.querySelector('[data-image-url-insert]');
        var imageLocalBtn = editor.querySelector('[data-image-local]');
        var uploadInput = editor.querySelector('[data-upload-input]');
        function uploadEditorImage(file){
            if(!file || !imageBtn) return;
            var fd = new FormData();
            fd.append('action', 'upload_content_image');
            fd.append('image_file', file);
            var csrf = form.querySelector('input[name="__csrf"]');
            if(csrf) fd.append('__csrf', csrf.value);
            imageBtn.disabled = true;
            imageBtn.textContent = '上传中...';
            fetch('<?php echo admin_h(cms_admin_url('content_center.php')); ?>', {method:'POST', body:fd, credentials:'same-origin'})
                .then(function(res){ return res.json(); })
                .then(function(ret){
                    if(ret && ret.ok && ret.url){
                        insertHtml(centeredImageHtml(ret.url, currentImageSize()));
                    }else{
                        alert((ret && ret.error) ? ret.error : '图片上传失败');
                    }
                })
                .catch(function(){ alert('图片上传失败，请检查网络或目录权限。'); })
                .finally(function(){
                    imageBtn.disabled = false;
                    imageBtn.textContent = '图片';
                    if(uploadInput) uploadInput.value = '';
                });
        }
        if(imageBtn && imagePanel){ imageBtn.addEventListener('click', function(){
            imagePanel.hidden = !imagePanel.hidden;
            if(!imagePanel.hidden && imageUrlInput) imageUrlInput.focus();
        }); }
        if(imageUrlInsert && imageUrlInput){
            imageUrlInsert.addEventListener('click', function(){
                var url = imageUrlInput.value.trim();
                if(!url) return;
                insertHtml(centeredImageHtml(url, currentImageSize()));
                imageUrlInput.value = '';
                if(imagePanel) imagePanel.hidden = true;
            });
            imageUrlInput.addEventListener('keydown', function(e){
                if(e.key === 'Enter'){
                    e.preventDefault();
                    imageUrlInsert.click();
                }
            });
        }
        if(imageLocalBtn && uploadInput){
            imageLocalBtn.addEventListener('click', function(){
                uploadInput.click();
            });
        }
        if(uploadInput){
            uploadInput.addEventListener('change', function(){
                var file = uploadInput.files && uploadInput.files[0];
                uploadEditorImage(file);
            });
        }
        var modeBtn = editor.querySelector('[data-mode="source"]');
        if(modeBtn){ modeBtn.addEventListener('click', function(){
            sourceMode = !sourceMode;
            if(sourceMode){
                syncToTextarea();
                canvas.hidden = true;
                textarea.hidden = false;
                this.classList.add('active');
            }else{
                syncToCanvas();
                textarea.hidden = true;
                canvas.hidden = false;
                this.classList.remove('active');
            }
        }); }
        var prevBtn = editor.querySelector('[data-preview]');
        if(prevBtn){ prevBtn.addEventListener('click', function(){
            syncToTextarea();
            preview.hidden = !preview.hidden;
            if(!preview.hidden) preview.innerHTML = textarea.value;
        }); }
        canvas.addEventListener('input', syncToTextarea);
        textarea.addEventListener('input', function(){ if(sourceMode) syncToCanvas(); });
        form.addEventListener('submit', syncToTextarea);
        syncToTextarea();
    }
})();
</script>
<?php admin_footer(); ?>
