<?php
/**
 * 前端内容管理 - 知识库/资讯/FAQ/品牌故事
 */
require_once dirname(__DIR__) . '/config/config.php';
$admin = auth_boot();
$pageTitle = '前端内容管理';
$pageKey   = 'content';

$err = $msg = '';

// 删除
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    db()->delete('tbs_content', 'id = ?', [(int)$_GET['id']]);
    action_log('content', 'delete', '#' . (int)$_GET['id']);
    header('Location: /admin/content.php'); exit;
}

// 切换发布状态
if (isset($_GET['action']) && $_GET['action'] === 'toggle' && isset($_GET['id'])) {
    $r = db()->row('SELECT status FROM tbs_content WHERE id = ?', [(int)$_GET['id']]);
    if ($r) {
        db()->update('tbs_content', ['status' => $r['status'] ? 0 : 1], 'id = ?', [(int)$_GET['id']]);
        action_log('content', 'toggle', '#' . (int)$_GET['id']);
    }
    header('Location: /admin/content.php'); exit;
}

// 编辑模式
$editRow = null;
if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
    $editRow = db()->row('SELECT * FROM tbs_content WHERE id = ?', [(int)$_GET['id']]);
}

// 保存 (新增/编辑)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id   = (int)($_POST['id'] ?? 0);
    $type = $_POST['type'] ?? 'knowledge';
    $data = [
        'title'        => trim($_POST['title'] ?? ''),
        'type'         => $type,
        'category'     => trim($_POST['category'] ?? ''),
        'summary'      => trim($_POST['summary'] ?? ''),
        'content'      => $_POST['content'] ?? '',
        'cover_image'  => trim($_POST['cover_image'] ?? ''),
        'seo_title'    => trim($_POST['seo_title'] ?? ''),
        'seo_keywords' => trim($_POST['seo_keywords'] ?? ''),
        'seo_description' => trim($_POST['seo_description'] ?? ''),
        'tags'         => trim($_POST['tags'] ?? ''),
        'author'       => trim($_POST['author'] ?? '盛木凡'),
        'sort_order'   => (int)($_POST['sort_order'] ?? 0),
        'is_featured'  => isset($_POST['is_featured']) ? 1 : 0,
        'status'       => isset($_POST['status']) ? 1 : 0,
    ];

    // 处理封面图上传
    if (!empty($_FILES['cover_file']['name'])) {
        $r = upload_file('cover_file', ['jpg','jpeg','png','gif','webp','svg'], 10 * 1024 * 1024);
        if ($r['ok']) {
            $data['cover_image'] = $r['path'];
            db()->insert('tbs_file', [
                'filename'      => $r['filename'],
                'original_name' => $r['original'],
                'file_path'     => $r['path'],
                'file_type'     => $r['type'],
                'file_size'     => $r['size'],
                'mime_type'     => $r['mime'],
                'category'      => 'image',
                'uploaded_by'   => $admin['id'],
            ]);
        } else {
            $err = '封面图上传失败: ' . $r['msg'];
        }
    }

    if (!empty($_POST['published_at'])) {
        $data['published_at'] = $_POST['published_at'];
    } elseif (empty($id)) {
        $data['published_at'] = date('Y-m-d H:i:s');
    }

    if ($data['title'] === '' || $data['content'] === '') {
        $err = '标题与内容必填';
    } else {
        $slug = make_slug($data['title']);
        $slug = unique_slug('tbs_content', $slug, $id);
        $data['slug'] = $slug;

        if ($id) {
            db()->update('tbs_content', $data, 'id = ?', [$id]);
            $msg = '已更新';
        } else {
            $id = db()->insert('tbs_content', $data);
            $msg = '已新增 #' . $id;
        }
        action_log('content', 'save', $type . ' #' . $id);
        header('Location: /admin/content.php?msg=' . urlencode($msg)); exit;
    }
}

if (!$msg && isset($_GET['msg'])) $msg = $_GET['msg'];

// 列表筛选
$type     = $_GET['type'] ?? '';
$status   = $_GET['status'] ?? '';
$category = $_GET['category'] ?? '';
$keyword  = trim($_GET['q'] ?? '');
$where = '1=1'; $params = [];
if ($type)     { $where .= ' AND type = ?';   $params[] = $type; }
if ($category) { $where .= ' AND category = ?'; $params[] = $category; }
if ($status !== '') { $where .= ' AND status = ?'; $params[] = (int)$status; }
if ($keyword)  { $where .= ' AND (title LIKE ? OR summary LIKE ?)'; $params[] = "%$keyword%"; $params[] = "%$keyword%"; }

$page = max(1, (int)($_GET['page'] ?? 1));
$res = db()->paginate('tbs_content', $where, $params, $page, 20);

$typeOptions = db()->all("SELECT dict_code, dict_label FROM tbs_dict WHERE dict_type = 'content_type' ORDER BY sort_order");

require __DIR__ . '/views/header.php';
require __DIR__ . '/views/sidebar.php';
?>
<div class="main-content">
    <div class="topbar">
        <div class="topbar-left"><span class="page-date">前端内容管理</span></div>
        <div class="topbar-right">
            <a class="btn btn-default btn-sm" href="?action=edit"><i class="bi bi-plus"></i> 新增内容</a>
        </div>
    </div>
    <div class="page-header"><h2 class="page-title">知识库 / FAQ / 营销 / 资讯</h2>
        <p class="page-sub">管理官网全部前端内容 · 每篇独立 SEO TKD</p>
    </div>

    <?php if ($err): ?><div class="alert alert-error"><?= e($err) ?></div><?php endif; ?>
    <?php if ($msg): ?><div class="alert alert-success auto-dismiss"><?= e($msg) ?></div><?php endif; ?>

    <?php if ($editRow || (isset($_GET['action']) && $_GET['action'] === 'edit')): ?>
    <div class="form-card">
        <h3 style="font-size:14px;font-weight:600;margin:0 0 12px"><?= $editRow ? '编辑' : '新增' ?>内容</h3>
        <form method="post" enctype="multipart/form-data">
    <?= csrf_field() ?>
    <input type="hidden" name="id" value="<?= (int)($editRow['id'] ?? 0) ?>">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-row">
                        <label class="form-label">标题 *</label>
                        <input class="form-control" name="title" required value="<?= e($editRow['title'] ?? '') ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-row">
                        <label class="form-label">类型 *</label>
                        <select class="form-control" name="type" required>
                            <?php foreach ($typeOptions as $to): ?>
                                <option value="<?= e($to['dict_code']) ?>" <?= ($editRow['type'] ?? '') === $to['dict_code'] ? 'selected' : '' ?>><?= e($to['dict_label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-row">
                        <label class="form-label">分类</label>
                        <input class="form-control" name="category" value="<?= e($editRow['category'] ?? '') ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-row">
                        <label class="form-label">排序</label>
                        <input class="form-control" type="number" name="sort_order" value="<?= (int)($editRow['sort_order'] ?? 0) ?>">
                    </div>
                </div>
            </div>
            <div class="form-row">
                <label class="form-label">摘要</label>
                <textarea class="form-control" name="summary" rows="2"><?= e($editRow['summary'] ?? '') ?></textarea>
            </div>
            <div class="form-row">
                <label class="form-label">正文 (HTML) *</label>
                <textarea class="form-control" name="content" rows="14" required><?= e($editRow['content'] ?? '') ?></textarea>
                <small class="form-help">支持 HTML 标签, FAQ 页面会自动输出 JSON-LD 结构化数据。</small>
            </div>
            <div class="form-row">
                <label class="form-label">封面图</label>
                <div style="display:flex;gap:10px;align-items:flex-start">
                    <div style="flex:1">
                        <input class="form-control" name="cover_image" value="<?= e($editRow['cover_image'] ?? '') ?>" placeholder="/uploads/images/xxx.jpg 或留空上传">
                        <input type="file" name="cover_file" accept="image/*" style="margin-top:6px;font-size:12px">
                        <small class="form-help">直接上传图片, 或填入已有 URL。留空则使用占位图。</small>
                    </div>
                    <?php if (!empty($editRow['cover_image'])): ?>
                        <img src="<?= e($editRow['cover_image']) ?>" style="width:80px;height:80px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb">
                    <?php endif; ?>
                </div>
            </div>
            <hr>
            <h4 style="font-size:13px;color:#4b5563">SEO 设置</h4>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">SEO 标题</label>
                        <input class="form-control" name="seo_title" value="<?= e($editRow['seo_title'] ?? '') ?>" placeholder="留空使用主标题">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">SEO 关键词</label>
                        <input class="form-control" name="seo_keywords" value="<?= e($editRow['seo_keywords'] ?? '') ?>" placeholder="逗号分隔">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">SEO 描述</label>
                        <input class="form-control" name="seo_description" value="<?= e($editRow['seo_description'] ?? '') ?>">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">标签</label>
                        <input class="form-control" name="tags" value="<?= e($editRow['tags'] ?? '') ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">作者</label>
                        <input class="form-control" name="author" value="<?= e($editRow['author'] ?? '盛木凡') ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label class="form-label">发布时间</label>
                        <input class="form-control" name="published_at" value="<?= e($editRow['published_at'] ?? '') ?>" placeholder="2024-01-01 12:00:00">
                    </div>
                </div>
            </div>
            <div class="form-row">
                <label><input type="checkbox" name="is_featured" value="1" <?= ($editRow['is_featured'] ?? 0) ? 'checked' : '' ?>> 推荐</label>
                <label style="margin-left:16px"><input type="checkbox" name="status" value="1" <?= (!$editRow || $editRow['status']) ? 'checked' : '' ?>> 发布</label>
            </div>
            <div>
                <button class="btn btn-primary" type="submit"><?= $editRow ? '更新' : '保存' ?></button>
                <a class="btn btn-default" href="/fmsmf/content.php">取消</a>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <div class="form-toolbar">
        <form method="get" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
            <select class="form-control" name="type" style="min-width:120px">
                <option value="">全部类型</option>
                <?php foreach ($typeOptions as $to): ?>
                    <option value="<?= e($to['dict_code']) ?>" <?= $type === $to['dict_code'] ? 'selected' : '' ?>><?= e($to['dict_label']) ?></option>
                <?php endforeach; ?>
            </select>
            <input class="form-control" name="category" value="<?= e($category) ?>" placeholder="分类 (如 产品)" style="min-width:140px">
            <select class="form-control" name="status" style="min-width:100px">
                <option value="">全部状态</option>
                <option value="1" <?= $status === '1' ? 'selected' : '' ?>>已发布</option>
                <option value="0" <?= $status === '0' ? 'selected' : '' ?>>草稿</option>
            </select>
            <input class="form-control" name="q" value="<?= e($keyword) ?>" placeholder="搜索标题/摘要">
            <button class="btn btn-primary" type="submit">筛选</button>
        </form>
        <div class="spacer"></div>
        <span class="text-muted" style="font-size:12px">共 <?= $res['total'] ?> 条</span>
    </div>

    <div class="form-card" style="padding:0">
        <table class="data-table">
            <thead><tr><th>标题</th><th>类型</th><th>分类</th><th>作者</th><th>浏览</th><th>状态</th><th>更新时间</th><th width="220">操作</th></tr></thead>
            <tbody>
            <?php if (empty($res['list'])): ?>
                <tr><td colspan="8" class="text-center text-muted" style="padding:30px">暂无数据</td></tr>
            <?php else: foreach ($res['list'] as $r): ?>
                <tr>
                    <td>
                        <strong><?= e($r['title']) ?></strong>
                        <?php if ($r['is_featured']): ?><span class="tag tag-warning" style="margin-left:4px">推荐</span><?php endif; ?>
                        <br><small class="text-muted">/<?= e($r['type']) ?>/<?= e($r['slug']) ?></small>
                    </td>
                    <td><span class="tag tag-info"><?= e($r['type']) ?></span></td>
                    <td><?= e($r['category']) ?></td>
                    <td><?= e($r['author']) ?></td>
                    <td><?= (int)$r['view_count'] ?></td>
                    <td>
                        <a href="?action=toggle&id=<?= (int)$r['id'] ?>" class="tag <?= $r['status'] ? 'tag-success' : 'tag-default' ?>" style="text-decoration:none">
                            <?= $r['status'] ? '已发布' : '草稿' ?>
                        </a>
                    </td>
                    <td><small class="text-muted"><?= e(time_ago($r['updated_at'])) ?></small></td>
                    <td>
                        <a class="btn btn-default btn-sm" href="?action=edit&id=<?= (int)$r['id'] ?>">编辑</a>
                        <a class="btn btn-default btn-sm" href="/web/content.php?slug=<?= e($r['slug']) ?>" target="_blank">预览</a>
                        <a class="btn btn-danger btn-sm" data-confirm="确认删除?" href="?action=delete&id=<?= (int)$r['id'] ?>">删除</a>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
        <?php if ($res['page_count'] > 1): ?>
            <div class="pagination">
                <?php for ($i = 1; $i <= $res['page_count']; $i++): ?>
                    <?php if ($i === $res['page']): ?><span class="active"><span><?= $i ?></span></span>
                    <?php else: ?><a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a><?php endif; ?>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// 封面图实时预览
document.addEventListener('change', function(e) {
    if (e.target.name === 'cover_file' && e.target.files[0]) {
        const f = e.target.files[0];
        if (!f.type.startsWith('image/')) return;
        const reader = new FileReader();
        reader.onload = function(ev) {
            let img = e.target.closest('div').parentElement.querySelector('img');
            if (!img) {
                img = document.createElement('img');
                img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb';
                e.target.closest('div').parentElement.appendChild(img);
            }
            img.src = ev.target.result;
        };
        reader.readAsDataURL(f);
    }
});
</script>

<?php require __DIR__ . '/views/footer.php'; ?>
