<?php
/**
 * 炎酷CMS - 栏目管理（树形列表 + 新增/编辑/删除）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require dirname(__DIR__) . '/inc/medialib.php';

$page_title = '栏目管理';
$active = 'column';
$T = DB_PREFIX . 'column';

// ---------- 写操作 ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $do = isset($_POST['do']) ? $_POST['do'] : '';

    if ($do === 'delete') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $col = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if (!$col) {
            flash_set('栏目不存在', 'err');
        } elseif ((int)db_val("SELECT COUNT(*) FROM $T WHERE pid = ?", array($id)) > 0) {
            flash_set('该栏目下存在子栏目，无法删除', 'err');
        } elseif ((int)db_val('SELECT COUNT(*) FROM ' . DB_PREFIX . 'article WHERE col_id = ?', array($id)) > 0) {
            flash_set('该栏目下存在文章，无法删除', 'err');
        } else {
            db_exec("DELETE FROM $T WHERE id = ?", array($id));
            admin_log('删除栏目', 'ID:' . $id . ' 名称:' . $col['name']);
            flash_set('栏目已删除');
        }
        header('Location: index.php');
        exit;
    }

    // 单页删除（单页管理已合并到本页 ?tab=page）
    if ($do === 'page_delete') {
        $id  = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $row = db_one('SELECT name FROM ' . DB_PREFIX . 'page WHERE id = ?', array($id));
        if ($row) {
            db_exec('DELETE FROM ' . DB_PREFIX . 'page WHERE id = ?', array($id));
            admin_log('删除单页', 'ID:' . $id . ' 名称:' . $row['name']);
            flash_set('单页已删除');
        }
        header('Location: index.php?tab=page');
        exit;
    }

    // 列表双击快速修改（栏目名称/排序），JSON 返回
    if ($do === 'ajax_save') {
        header('Content-Type: application/json; charset=utf-8');
        $id    = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $field = isset($_POST['field']) ? $_POST['field'] : '';
        if (!in_array($field, array('name', 'sort'), true)) {
            echo json_encode(array('code' => 1, 'msg' => '不允许修改的字段'), JSON_UNESCAPED_UNICODE);
            exit;
        }
        $value = $field === 'name' ? trim((string)(isset($_POST['value']) ? $_POST['value'] : ''))
                                   : (int)(isset($_POST['value']) ? $_POST['value'] : 0);
        if ($field === 'name' && $value === '') {
            echo json_encode(array('code' => 1, 'msg' => '栏目名称不能为空'), JSON_UNESCAPED_UNICODE);
            exit;
        }
        db_exec("UPDATE $T SET `$field` = ? WHERE id = ?", array($value, $id));
        admin_log('快速修改栏目', 'ID:' . $id . ' 字段:' . $field);
        echo json_encode(array('code' => 0, 'msg' => 'ok'), JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 单页双击快速修改（名称/排序），JSON 返回
    if ($do === 'ajax_save_page') {
        header('Content-Type: application/json; charset=utf-8');
        $id    = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $field = isset($_POST['field']) ? $_POST['field'] : '';
        if (!in_array($field, array('name', 'sort'), true)) {
            echo json_encode(array('code' => 1, 'msg' => '不允许修改的字段'), JSON_UNESCAPED_UNICODE);
            exit;
        }
        $value = $field === 'name' ? trim((string)(isset($_POST['value']) ? $_POST['value'] : ''))
                                   : (int)(isset($_POST['value']) ? $_POST['value'] : 0);
        if ($field === 'name' && $value === '') {
            echo json_encode(array('code' => 1, 'msg' => '单页名称不能为空'), JSON_UNESCAPED_UNICODE);
            exit;
        }
        db_exec('UPDATE ' . DB_PREFIX . "page SET `$field` = ? WHERE id = ?", array($value, $id));
        admin_log('快速修改单页', 'ID:' . $id . ' 字段:' . $field);
        echo json_encode(array('code' => 0, 'msg' => 'ok'), JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($do === 'save') {
        $id    = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $pid   = (int)(isset($_POST['pid']) ? $_POST['pid'] : 0);
        $name  = trim(isset($_POST['name']) ? $_POST['name'] : '');
        if ($name === '') {
            flash_set('栏目名称不能为空', 'err');
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php'));
            exit;
        }
        // 父级不能是自身或自身后代
        if ($id > 0 && $pid > 0 && in_array($pid, column_descendant_ids($id))) {
            flash_set('父级栏目不能选择自身或其子栏目', 'err');
            header('Location: index.php?act=edit&id=' . $id);
            exit;
        }
        // flag（伪静态目录式地址别名）校验：可空，字母/数字/下划线/横线，栏目间唯一
        $flag = trim(isset($_POST['flag']) ? $_POST['flag'] : '');
        if ($flag !== '') {
            if (!preg_match('/^[a-zA-Z0-9_-]+$/', $flag)) {
                flash_set('地址别名只能包含字母、数字、下划线和横线', 'err');
                header('Location: index.php' . ($id > 0 ? '?act=edit&id=' . $id : '?act=add'));
                exit;
            }
            $dup = db_one("SELECT id FROM $T WHERE flag = ? AND id != ?", array($flag, $id));
            if ($dup) {
                flash_set('地址别名 ' . $flag . ' 已被其他栏目占用', 'err');
                header('Location: index.php' . ($id > 0 ? '?act=edit&id=' . $id : '?act=add'));
                exit;
            }
        }
        $data = array(
            'pid'             => $pid,
            'name'            => $name,
            'nav_name'        => trim(isset($_POST['nav_name']) ? $_POST['nav_name'] : ''),
            'flag'            => $flag,
            'is_nav'          => !empty($_POST['is_nav']) ? 1 : 0,
            'intro'           => trim(isset($_POST['intro']) ? $_POST['intro'] : ''),
            'cover'           => trim(isset($_POST['cover']) ? $_POST['cover'] : ''),
            'list_tpl'        => 1, // 列表模板由【在线编辑】可视化管理；编辑时下方会回填数据库原值
            'content_tpl'     => 1, // 内容页模板由【在线编辑】可视化管理；编辑时下方会回填数据库原值
            'page_size'       => max(1, min(100, (int)(isset($_POST['page_size']) ? $_POST['page_size'] : 10))),
            '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) {
            // 列表模板/内容页模板不在本表单维护（见左侧菜单【在线编辑】），保留数据库原值
            $keepTpl = db_one("SELECT list_tpl, content_tpl FROM $T WHERE id = ?", array($id));
            if ($keepTpl) {
                $data['list_tpl'] = max(1, (int)$keepTpl['list_tpl']);
                $data['content_tpl'] = max(1, (int)$keepTpl['content_tpl']);
            }
            db_exec("UPDATE $T SET pid=?, name=?, nav_name=?, flag=?, is_nav=?, intro=?, cover=?, list_tpl=?, content_tpl=?, page_size=?, seo_title=?, seo_keywords=?, seo_description=?, sort=?, status=? WHERE id=?",
                array($data['pid'], $data['name'], $data['nav_name'], $data['flag'], $data['is_nav'], $data['intro'], $data['cover'], $data['list_tpl'], $data['content_tpl'], $data['page_size'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status'], $id));
            admin_log('编辑栏目', 'ID:' . $id . ' 名称:' . $data['name']);
            flash_set('栏目已保存');
        } else {
            $id = db_insert("INSERT INTO $T (pid, name, nav_name, flag, is_nav, intro, cover, list_tpl, content_tpl, page_size, seo_title, seo_keywords, seo_description, sort, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                array($data['pid'], $data['name'], $data['nav_name'], $data['flag'], $data['is_nav'], $data['intro'], $data['cover'], $data['list_tpl'], $data['content_tpl'], $data['page_size'], $data['seo_title'], $data['seo_keywords'], $data['seo_description'], $data['sort'], $data['status']));
            admin_log('新增栏目', 'ID:' . $id . ' 名称:' . $data['name']);
            flash_set('栏目已新增');
        }
        header('Location: index.php');
        exit;
    }
}

// ---------- 新增/编辑表单 ----------
$act = isset($_GET['act']) ? $_GET['act'] : '';
if ($act === 'add' || $act === 'edit') {
    $row = array('id' => 0, 'pid' => 0, 'name' => '', 'nav_name' => '', 'flag' => '', 'is_nav' => 1, 'intro' => '', 'cover' => '',
        'list_tpl' => 1, 'content_tpl' => 1, 'page_size' => 10,
        'seo_title' => '', 'seo_keywords' => '', 'seo_description' => '', 'sort' => 0, 'status' => 1);
    $excludeIds = array();
    if ($act === 'edit') {
        $id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
        $row = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if (!$row) { flash_set('栏目不存在', 'err'); header('Location: index.php'); exit; }
        $excludeIds = column_descendant_ids($row['id']);
        $page_title = '编辑栏目';
    } else {
        $page_title = '新增栏目';
    }
    $options = column_options();
    require dirname(__DIR__) . '/inc/header.php';
    ?>
<div class="yk-card">
  <h3><?php echo e($page_title); ?></h3>
  <form class="yk-form" method="post" action="index.php">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="do" value="save">
    <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
    <div class="row"><label>父级栏目</label><div class="ipt"><select name="pid">
      <option value="0">顶级栏目</option>
      <?php foreach ($options as $o): if (in_array($o['id'], $excludeIds)) continue; ?>
      <option value="<?php echo (int)$o['id']; ?>"<?php echo (int)$row['pid'] === (int)$o['id'] ? ' selected' : ''; ?>><?php echo str_repeat('　', $o['depth']) . e($o['name']); ?></option>
      <?php endforeach; ?>
    </select></div></div>
    <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>地址别名 flag</label><div class="ipt"><input type="text" name="flag" value="<?php echo e(isset($row['flag']) ? $row['flag'] : ''); ?>"><div class="tip">伪静态开启后栏目地址为 /别名/（如 product、news），可填英文或栏目名拼音（如 chanpinzhongxin）；留空则用 /col-ID.html</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>栏目简介</label><div class="ipt"><textarea name="intro" rows="3"><?php echo e($row['intro']); ?></textarea></div></div>
    <?php yk_image_field('cover', $row['cover'], '栏目封面'); ?>
    <div class="row"><label>列表模板</label><div class="ipt"><div class="tip" style="padding-top:8px">当前：样式<?php echo (int)$row['list_tpl']; ?>（在左侧菜单【在线编辑】→“文章列表”中可视化修改）</div></div></div>
    <div class="row"><label>内容页模板</label><div class="ipt"><div class="tip" style="padding-top:8px">当前：样式<?php echo (int)$row['content_tpl']; ?>（在左侧菜单【在线编辑】→“文章内容”中可视化修改）</div></div></div>
    <div class="row"><label>每页条数</label><div class="ipt"><input type="number" name="page_size" min="1" max="100" value="<?php echo (int)$row['page_size']; ?>"></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 class="tip">数字越小越靠前</div></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>
    <?php
    require dirname(__DIR__) . '/inc/footer.php';
    exit;
}

// ---------- 树形列表 ----------
function yk_col_tree_rows($pid = 0, $depth = 0, &$out = array()) {
    $rows = db_all('SELECT * FROM ' . DB_PREFIX . 'column WHERE pid = ? ORDER BY sort ASC, id ASC', array($pid));
    foreach ($rows as $r) {
        $r['depth'] = $depth;
        $r['art_num'] = (int)db_val('SELECT COUNT(*) FROM ' . DB_PREFIX . 'article WHERE col_id = ?', array($r['id']));
        $out[] = $r;
        yk_col_tree_rows($r['id'], $depth + 1, $out);
    }
    return $out;
}
$cols = yk_col_tree_rows();
$tab  = isset($_GET['tab']) && $_GET['tab'] === 'page' ? 'page' : 'col';
$pages = $tab === 'page'
    ? db_all('SELECT * FROM ' . DB_PREFIX . 'page ORDER BY sort ASC, id ASC')
    : array();

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-tabs">
  <a href="index.php"<?php echo $tab === 'col' ? ' class="on"' : ''; ?>>栏目列表</a>
  <a href="index.php?tab=page"<?php echo $tab === 'page' ? ' class="on"' : ''; ?>>单页管理</a>
</div>
<?php if ($tab === 'page'): ?>
<div class="yk-card">
  <h3>单页列表 <a class="yk-btn sm" href="../page/edit.php" style="float:right">+ 新增单页</a></h3>
  <table class="yk-table">
    <tr><th width="60">ID</th><th>名称</th><th width="120">标识 flag</th><th width="90">模板</th><th width="60">排序</th><th width="60">状态</th><th width="130">操作</th></tr>
    <?php foreach ($pages as $p): ?>
    <tr>
      <td><?php echo (int)$p['id']; ?></td>
      <td class="yk-ed" data-id="<?php echo (int)$p['id']; ?>" data-field="name" title="双击快速修改"><?php echo e($p['name']); ?></td>
      <td><?php echo e($p['flag']); ?></td>
      <td>模板 <?php echo (int)$p['page_tpl']; ?></td>
      <td class="yk-ed" data-id="<?php echo (int)$p['id']; ?>" data-field="sort" title="双击快速修改"><?php echo (int)$p['sort']; ?></td>
      <td><?php echo $p['status'] ? '<span style="color:#1a9b4c">启用</span>' : '<span style="color:#d93025">停用</span>'; ?></td>
      <td class="yk-actions" style="white-space:nowrap">
        <a href="<?php echo e(SITE_URL); ?>/?page=<?php echo e($p['flag']); ?>" target="_blank">预览</a>
        <a href="../page/edit.php?id=<?php echo (int)$p['id']; ?>">编辑</a>
        <form method="post" action="index.php?tab=page" style="display:inline" onsubmit="return confirm('确定删除该单页？');">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="page_delete">
          <input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$pages): ?><tr><td colspan="7" style="text-align:center;color:#999">暂无单页</td></tr><?php endif; ?>
  </table>
</div>
<script>
// 单页列表双击快速修改（名称/排序）
var YK_CSRF = <?php echo json_encode(csrf_token()); ?>;
document.querySelectorAll('.yk-ed').forEach(function (td) {
    td.style.cursor = 'pointer';
    td.ondblclick = function () {
        if (td.querySelector('input')) return;
        var old = td.textContent.trim();
        var inp = document.createElement('input');
        inp.type = td.getAttribute('data-field') === 'name' ? 'text' : 'number';
        inp.value = old;
        inp.style.cssText = 'width:100%;padding:4px 6px;border:1px solid #3b82f6;border-radius:4px;font-size:13px';
        td.textContent = '';
        td.appendChild(inp);
        inp.focus();
        inp.select();
        var done = false;
        function restore() { done = true; td.textContent = old; }
        function save() {
            if (done) return;
            done = true;
            var v = inp.value.trim();
            if (v === old) { td.textContent = old; return; }
            var fd = new FormData();
            fd.append('csrf_token', YK_CSRF);
            fd.append('do', 'ajax_save_page');
            fd.append('id', td.getAttribute('data-id'));
            fd.append('field', td.getAttribute('data-field'));
            fd.append('value', v);
            fetch('index.php?tab=page', {method: 'POST', body: fd, credentials: 'same-origin'})
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.code === 0) { td.textContent = v; }
                    else { alert(res.msg || '保存失败'); td.textContent = old; }
                })
                .catch(function () { td.textContent = old; });
        }
        inp.onblur = save;
        inp.onkeydown = function (e) {
            if (e.key === 'Enter') { inp.blur(); }
            if (e.key === 'Escape') { restore(); }
        };
    };
});
</script>
<?php require dirname(__DIR__) . '/inc/footer.php'; exit; endif; ?>
<div class="yk-card">
  <h3>栏目列表 <a class="yk-btn sm" href="index.php?act=add" style="float:right">+ 新增栏目</a></h3>
  <table class="yk-table">
    <tr><th width="60">ID</th><th>栏目名称</th><th width="80">文章数</th><th width="80">列表模板</th><th width="70">每页</th><th width="60">排序</th><th width="60">状态</th><th width="150">操作</th></tr>
    <?php foreach ($cols as $c): ?>
    <tr>
      <td><?php echo (int)$c['id']; ?></td>
      <td class="yk-ed" data-id="<?php echo (int)$c['id']; ?>" data-field="name" data-value="<?php echo e($c['name']); ?>" title="双击快速修改"><?php echo str_repeat('└ ', $c['depth']) . e($c['name']); ?></td>
      <td><?php echo $c['art_num']; ?></td>
      <td>模板 <?php echo (int)$c['list_tpl']; ?></td>
      <td><?php echo (int)$c['page_size']; ?></td>
      <td class="yk-ed" data-id="<?php echo (int)$c['id']; ?>" data-field="sort" title="双击快速修改"><?php echo (int)$c['sort']; ?></td>
      <td><?php echo $c['status'] ? '<span style="color:#1a9b4c">启用</span>' : '<span style="color:#d93025">停用</span>'; ?></td>
      <td class="yk-actions">
        <a href="<?php echo e(SITE_URL); ?>/index.php?col=<?php echo (int)$c['id']; ?>" target="_blank">预览</a>
        <a href="index.php?act=edit&amp;id=<?php echo (int)$c['id']; ?>">编辑</a>
        <form method="post" action="index.php" style="display:inline" onsubmit="return confirm('确定删除该栏目？');">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="delete">
          <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$cols): ?><tr><td colspan="8" style="text-align:center;color:#999">暂无栏目，请先新增</td></tr><?php endif; ?>
  </table>
</div>
<script>
// 列表双击快速修改（栏目名称/排序）
var YK_CSRF = <?php echo json_encode(csrf_token()); ?>;
document.querySelectorAll('.yk-ed').forEach(function (td) {
    td.style.cursor = 'pointer';
    td.ondblclick = function () {
        if (td.querySelector('input')) return;
        var prefix = '';
        var old = td.textContent.trim();
        var m = old.match(/^((?:└ )+)(.*)$/);
        if (m) { prefix = m[1]; old = m[2]; } // 去掉树形前缀，保存纯名称
        var inp = document.createElement('input');
        inp.type = td.getAttribute('data-field') === 'name' ? 'text' : 'number';
        inp.value = old;
        inp.style.cssText = 'width:100%;padding:4px 6px;border:1px solid #3b82f6;border-radius:4px;font-size:13px';
        td.textContent = '';
        td.appendChild(inp);
        inp.focus();
        inp.select();
        var done = false;
        function restore() { done = true; td.textContent = prefix + old; }
        function save() {
            if (done) return;
            done = true;
            var v = inp.value.trim();
            if (v === old) { td.textContent = prefix + old; return; }
            var fd = new FormData();
            fd.append('csrf_token', YK_CSRF);
            fd.append('do', 'ajax_save');
            fd.append('id', td.getAttribute('data-id'));
            fd.append('field', td.getAttribute('data-field'));
            fd.append('value', v);
            fetch('index.php', {method: 'POST', body: fd, credentials: 'same-origin'})
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.code === 0) { td.textContent = prefix + v; }
                    else { alert(res.msg || '保存失败'); td.textContent = prefix + old; }
                })
                .catch(function () { td.textContent = prefix + old; });
        }
        inp.onblur = save;
        inp.onkeydown = function (e) {
            if (e.key === 'Enter') { inp.blur(); }
            if (e.key === 'Escape') { restore(); }
        };
    };
});
</script>
<?php require dirname(__DIR__) . '/inc/footer.php'; ?>
