<?php
/**
 * 炎酷CMS - 文章发布/编辑（UEditor 内容编辑 + 图库缩略图 + 多图图集）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require dirname(__DIR__) . '/inc/medialib.php';
require dirname(__DIR__) . '/inc/content.php';

$active = 'article';
$T = DB_PREFIX . 'article';

$id = (int)(isset($_REQUEST['id']) ? $_REQUEST['id'] : 0);

// ---------- 保存 ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $title = trim(isset($_POST['title']) ? $_POST['title'] : '');
    if ($title === '') {
        flash_set('文章标题不能为空', 'err');
        header('Location: edit.php' . ($id ? '?id=' . $id : ''));
        exit;
    }
    $content = isset($_POST['content']) ? $_POST['content'] : '';
    // 内容选项：自动上传外部图片（先）→ 删除内容中的网址（后）
    $content = yk_content_prepare($content);
    // 缩略图：为空时自动从内容抓取第一个本站 uploads/ 图片
    $thumb = trim(isset($_POST['thumb']) ? $_POST['thumb'] : '');
    if ($thumb === '' && preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $content, $m)) {
        if (preg_match('#(uploads/[^\s"\'<>]+)#i', $m[1], $mm)) {
            $thumb = $mm[1];
        }
    }
    // 图集：多行图片输入 photos[] 转 JSON 数组
    $photos = array();
    if (!empty($_POST['photos']) && is_array($_POST['photos'])) {
        foreach ($_POST['photos'] as $p) {
            $p = trim($p);
            if ($p !== '') $photos[] = $p;
        }
    }
    // 发布时间：可修改，新增留空则当前时间，编辑留空保持原值
    $addTime = 0;
    $addTimeStr = trim(isset($_POST['add_time']) ? $_POST['add_time'] : '');
    if ($addTimeStr !== '') {
        $addTime = strtotime(str_replace('T', ' ', $addTimeStr));
        if ($addTime === false) $addTime = 0;
    }
    $data = array(
        'col_id'          => (int)(isset($_POST['col_id']) ? $_POST['col_id'] : 0),
        'title'           => $title,
        'thumb'           => $thumb,
        'photos'          => json_encode($photos, JSON_UNESCAPED_UNICODE),
        'content'         => $content,
        'is_top'          => !empty($_POST['is_top']) ? 1 : 0,
        'is_recommend'    => !empty($_POST['is_recommend']) ? 1 : 0,
        'seo_title'       => trim(isset($_POST['seo_title']) ? $_POST['seo_title'] : ''),
        'seo_keywords'    => trim(isset($_POST['seo_keywords']) ? $_POST['seo_keywords'] : ''),
        'seo_description' => trim(isset($_POST['seo_description']) ? $_POST['seo_description'] : ''),
        'sort'            => (int)(isset($_POST['sort']) ? $_POST['sort'] : 0),
        'status'          => !empty($_POST['status']) ? 1 : 0,
    );
    if ($id > 0) {
        if ($addTime > 0) {
            db_exec("UPDATE $T SET col_id=?, title=?, thumb=?, photos=?, content=?, add_time=?, is_top=?, is_recommend=?, seo_title=?, seo_keywords=?, seo_description=?, sort=?, status=? WHERE id=?",
                array($data['col_id'], $data['title'], $data['thumb'], $data['photos'], $data['content'], $addTime, $data['is_top'], $data['is_recommend'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status'], $id));
        } else {
            db_exec("UPDATE $T SET col_id=?, title=?, thumb=?, photos=?, content=?, is_top=?, is_recommend=?, seo_title=?, seo_keywords=?, seo_description=?, sort=?, status=? WHERE id=?",
                array($data['col_id'], $data['title'], $data['thumb'], $data['photos'], $data['content'], $data['is_top'], $data['is_recommend'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status'], $id));
        }
        admin_log('编辑文章', 'ID:' . $id . ' 标题:' . $title);
        flash_set('文章已保存');
    } else {
        $id = db_insert("INSERT INTO $T (col_id, title, thumb, photos, content, add_time, is_top, is_recommend, views, seo_title, seo_keywords, seo_description, sort, status) VALUES (?,?,?,?,?,?,?,?,0,?,?,?,?,?)",
            array($data['col_id'], $data['title'], $data['thumb'], $data['photos'], $data['content'], $addTime > 0 ? $addTime : time(), $data['is_top'], $data['is_recommend'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status']));
        admin_log('发布文章', 'ID:' . $id . ' 标题:' . $title);
        flash_set('文章已发布');
    }
    header('Location: index.php');
    exit;
}

// ---------- 表单 ----------
$row = array('id' => 0, 'col_id' => 0, 'title' => '', 'thumb' => '', 'photos' => '[]', 'content' => '',
    'add_time' => time(), 'is_top' => 0, 'is_recommend' => 0, 'seo_title' => '', 'seo_keywords' => '', 'seo_description' => '',
    'sort' => 0, 'status' => 1);
$page_title = '发布文章';
if ($id > 0) {
    $row = db_one("SELECT * FROM $T WHERE id = ?", array($id));
    if (!$row) { flash_set('文章不存在', 'err'); header('Location: index.php'); exit; }
    $page_title = '编辑文章';
}
// 图集 JSON 还原为数组
$photoArr = json_decode($row['photos'], true);
if (!is_array($photoArr)) $photoArr = array();
$colOptions = column_options();
// 防止内容中的 </script> 提前闭合编辑器容器
$editorHtml = str_replace('</script', '<\/script', $row['content']);

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3><?php echo e($page_title); ?></h3>
  <form class="yk-form" method="post" action="edit.php<?php echo $id ? '?id=' . $id : ''; ?>">
    <?php echo csrf_field(); ?>
    <div class="row"><label>文章标题</label><div class="ipt"><input type="text" name="title" value="<?php echo e($row['title']); ?>" required></div></div>
    <div class="row"><label>所属栏目</label><div class="ipt"><select name="col_id">
      <option value="0">未分类</option>
      <?php foreach ($colOptions as $o): ?>
      <option value="<?php echo (int)$o['id']; ?>"<?php echo (int)$row['col_id'] === (int)$o['id'] ? ' selected' : ''; ?>><?php echo str_repeat('　', $o['depth']) . e($o['name']); ?></option>
      <?php endforeach; ?>
    </select></div></div>
    <?php yk_image_field('thumb', $row['thumb'], '缩略图', '留空则自动提取内容中第一张本站图片作为缩略图'); ?>
    <div class="row"><label>图集</label><div class="ipt">
      <div id="ykPhotoRows">
        <?php foreach ($photoArr as $p): ?>
        <div class="yk-photo-row" style="display:flex;gap:8px;align-items:center;margin-bottom:8px">
          <input type="text" name="photos[]" value="<?php echo e($p); ?>" placeholder="图片路径" style="flex:1">
          <button type="button" class="yk-btn gray sm yk-photo-lib">图库</button>
          <button type="button" class="yk-btn red sm" onclick="this.parentNode.remove()">删除</button>
        </div>
        <?php endforeach; ?>
      </div>
      <button type="button" class="yk-btn gray sm" onclick="ykPhotoAdd()">+ 添加图片</button>
      <div class="tip">产品/案例多图展示用，保存为 JSON 图集</div>
    </div></div>
    <div class="row"><label>文章内容</label><div class="ipt" style="max-width:860px">
      <div id="ykEditorWrap"><script id="editor" type="text/plain"><?php echo $editorHtml; ?></script></div>
      <div class="tip">可视化编辑器（UEditor），支持图片上传与远程图自动转存</div>
      <div class="yk-check" style="margin-top:6px">
        <label><input type="checkbox" name="opt_strip_url" value="1" checked> 删除内容中的网址</label>
        <label><input type="checkbox" name="opt_auto_img" value="1" checked> 自动上传内容中的图片</label>
      </div>
    </div></div>
    <div class="row"><label>属性</label><div class="ipt yk-check">
      <label><input type="checkbox" name="is_top" value="1"<?php echo $row['is_top'] ? ' checked' : ''; ?>> 置顶</label>
      <label><input type="checkbox" name="is_recommend" value="1"<?php echo $row['is_recommend'] ? ' checked' : ''; ?>> 推荐</label>
      <label><input type="checkbox" name="status" value="1"<?php echo $row['status'] ? ' checked' : ''; ?>> 发布（不勾选为草稿）</label>
    </div></div>
    <div class="row"><label>排序</label><div class="ipt"><input type="number" name="sort" value="<?php echo (int)$row['sort']; ?>"><div class="tip">数字越小越靠前</div></div></div>
    <div class="row"><label>发布时间</label><div class="ipt"><input type="datetime-local" name="add_time" value="<?php echo e(date('Y-m-d\TH:i', (int)$row['add_time'])); ?>" style="max-width:240px"><div class="tip">可修改文章的发布日期</div></div></div>
    <div class="row"><label>SEO 标题</label><div class="ipt"><input type="text" name="seo_title" value="<?php echo e($row['seo_title']); ?>"><div class="tip">留空则使用文章标题</div></div></div>
    <div class="row"><label>SEO 关键词</label><div class="ipt"><input type="text" name="seo_keywords" value="<?php echo e($row['seo_keywords']); ?>"></div></div>
    <div class="row"><label>SEO 描述</label><div class="ipt"><textarea name="seo_description" rows="2"><?php echo e($row['seo_description']); ?></textarea></div></div>
    <div class="row"><label></label><div class="ipt">
      <button class="yk-btn" type="submit">保存</button>
      <a class="yk-btn gray" href="index.php">返回列表</a>
    </div></div>
  </form>
</div>
<script>
// 图集行编辑器
var ykPhotoSeq = 0;
function ykPhotoBind(row) {
    var imgInput = row.querySelector('input[name="photos[]"]');
    if (!imgInput.id) {
        ykPhotoSeq++;
        imgInput.id = 'yk_photo_' + ykPhotoSeq;
    }
    row.querySelector('.yk-photo-lib').onclick = function () { ykMediaPick(imgInput.id); };
}
function ykPhotoAdd(url) {
    url = url || '';
    var row = document.createElement('div');
    row.className = 'yk-photo-row';
    row.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:8px';
    row.innerHTML = '<input type="text" name="photos[]" placeholder="图片路径" style="flex:1">'
        + '<button type="button" class="yk-btn gray sm yk-photo-lib">图库</button>'
        + '<button type="button" class="yk-btn red sm" onclick="this.parentNode.remove()">删除</button>';
    document.getElementById('ykPhotoRows').appendChild(row);
    row.querySelector('input[name="photos[]"]').value = url;
    ykPhotoBind(row);
}
document.querySelectorAll('#ykPhotoRows .yk-photo-row').forEach(ykPhotoBind);
</script>
<script src="<?php echo e(SITE_URL); ?>/assets/ueditor/ueditor.config.js"></script>
<script src="<?php echo e(SITE_URL); ?>/assets/ueditor/ueditor.all.min.js"></script>
<script>
// UEditor 资源未就位时兜底为普通 textarea
if (window.UE && UE.getEditor) {
    UE.getEditor('editor', {
        serverUrl: <?php echo json_encode(SITE_URL . '/api/ueditor.php'); ?>,
        textarea: 'content',
        initialFrameWidth: '100%',
        initialFrameHeight: 420
    });
} else {
    (function () {
        var old = document.getElementById('editor');
        var ta = document.createElement('textarea');
        ta.name = 'content';
        ta.id = 'editor';
        ta.rows = 16;
        ta.style.width = '100%';
        ta.value = old.textContent || old.innerText || '';
        old.parentNode.replaceChild(ta, old);
    })();
}
</script>
<?php
yk_medialib_assets();
require dirname(__DIR__) . '/inc/footer.php';
