<?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 = 'column';
$T = DB_PREFIX . 'page';
$id = (int)(isset($_REQUEST['id']) ? $_REQUEST['id'] : 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $name = trim(isset($_POST['name']) ? $_POST['name'] : '');
    $flag = trim(isset($_POST['flag']) ? $_POST['flag'] : '');
    if ($name === '' || $flag === '') {
        flash_set('名称和标识不能为空', 'err');
        header('Location: edit.php' . ($id ? '?id=' . $id : ''));
        exit;
    }
    if (!preg_match('/^[a-zA-Z0-9_-]+$/', $flag)) {
        flash_set('标识只能包含字母、数字、下划线和横线', 'err');
        header('Location: edit.php' . ($id ? '?id=' . $id : ''));
        exit;
    }
    // flag 唯一校验
    $dup = db_one("SELECT id FROM $T WHERE flag = ? AND id != ?", array($flag, $id));
    if ($dup) {
        flash_set('标识 ' . $flag . ' 已被占用', 'err');
        header('Location: edit.php' . ($id ? '?id=' . $id : ''));
        exit;
    }
    $data = array(
        'name'            => $name,
        'nav_name'        => trim(isset($_POST['nav_name']) ? $_POST['nav_name'] : ''),
        'flag'            => $flag,
        'content'         => yk_content_prepare(isset($_POST['content']) ? $_POST['content'] : ''),
        'image'           => trim(isset($_POST['image']) ? $_POST['image'] : ''),
        'page_tpl'        => 1, // 页面模板由【在线编辑】可视化管理；编辑时下方会回填数据库原值
        '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,
        'is_nav'          => !empty($_POST['is_nav']) ? 1 : 0,
    );
    if ($id > 0) {
        // 页面模板不在本表单维护（见左侧菜单【在线编辑】），保留数据库原值
        $data['page_tpl'] = max(1, (int)db_val("SELECT page_tpl FROM $T WHERE id = ?", array($id)));
        db_exec("UPDATE $T SET name=?, nav_name=?, flag=?, content=?, image=?, page_tpl=?, seo_title=?, seo_keywords=?, seo_description=?, sort=?, status=?, is_nav=? WHERE id=?",
            array($data['name'], $data['nav_name'], $data['flag'], $data['content'], $data['image'], $data['page_tpl'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status'], $data['is_nav'], $id));
        admin_log('编辑单页', 'ID:' . $id . ' 名称:' . $name);
        flash_set('单页已保存');
    } else {
        $id = db_insert("INSERT INTO $T (name, nav_name, flag, content, image, page_tpl, seo_title, seo_keywords, seo_description, sort, status, is_nav) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
            array($data['name'], $data['nav_name'], $data['flag'], $data['content'], $data['image'], $data['page_tpl'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status'], $data['is_nav']));
        admin_log('新增单页', 'ID:' . $id . ' 名称:' . $name);
        flash_set('单页已新增');
    }
    header('Location: index.php');
    exit;
}

$row = array('id' => 0, 'name' => '', 'nav_name' => '', 'flag' => '', 'content' => '', 'image' => '', 'page_tpl' => 1,
    'seo_title' => '', 'seo_keywords' => '', 'seo_description' => '', 'sort' => 0, 'status' => 1, 'is_nav' => 0);
$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 = '编辑单页';
}
// 防止内容中的 </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="name" value="<?php echo e($row['name']); ?>" required></div></div>
    <div class="row"><label>导航显示名</label><div class="ipt"><input type="text" name="nav_name" value="<?php echo e($row['nav_name']); ?>"><div class="tip">留空则用单页名称；导航显示以此为准</div></div></div>
    <div class="row"><label>导航显示</label><div class="ipt yk-check"><label><input type="checkbox" name="is_nav" value="1"<?php echo $row['is_nav'] ? ' checked' : ''; ?>> 在导航中显示该单页</label></div></div>
    <div class="row"><label>唯一标识 flag</label><div class="ipt"><input type="text" name="flag" value="<?php echo e($row['flag']); ?>" required><div class="tip">字母/数字/下划线/横线，如 about、contact</div></div></div>
    <?php yk_image_field('image', $row['image'], '栏目封面', '作为单页顶部 banner 背景显示，也供首页「关于我们/联系我们」模块调用'); ?>
    <div class="row"><label>页面模板</label><div class="ipt"><div class="tip" style="padding-top:8px">当前：样式<?php echo (int)$row['page_tpl']; ?>（在左侧菜单【在线编辑】→“单页面”中可视化修改）</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>SEO 标题</label><div class="ipt"><input type="text" name="seo_title" value="<?php echo e($row['seo_title']); ?>"></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"><input type="number" name="sort" value="<?php echo (int)$row['sort']; ?>"></div></div>
    <div class="row"><label>状态</label><div class="ipt yk-check"><label><input type="checkbox" name="status" value="1"<?php echo $row['status'] ? ' checked' : ''; ?>> 启用</label></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 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';
