<?php
/**
 * 炎酷CMS - 文章管理（列表/筛选/分页/批量删除/批量移动栏目）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require dirname(__DIR__) . '/inc/content.php';

$page_title = '文章管理';
$active = 'article';
$T = DB_PREFIX . 'article';

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

    // 列表双击快速修改（标题/浏览量/排序），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('title', 'views', 'sort'), true)) {
            echo json_encode(array('code' => 1, 'msg' => '不允许修改的字段'), JSON_UNESCAPED_UNICODE);
            exit;
        }
        $value = $field === 'title' ? trim((string)(isset($_POST['value']) ? $_POST['value'] : ''))
                                    : (int)(isset($_POST['value']) ? $_POST['value'] : 0);
        if ($field === 'title' && $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;
    }

    $ids = array();
    if (!empty($_POST['ids']) && is_array($_POST['ids'])) {
        foreach ($_POST['ids'] as $v) $ids[] = (int)$v;
        $ids = array_filter($ids);
    }

    if ($do === 'delete_one') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $row = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if ($row) {
            // 级联删除文章引用到的 uploads 图片（物理文件 + 素材记录）
            yk_delete_upload_files(yk_article_upload_paths($row));
            db_exec("DELETE FROM $T WHERE id = ?", array($id));
            admin_log('删除文章', 'ID:' . $id . ' 标题:' . $row['title']);
            flash_set('文章已删除');
        }
    } elseif ($do === 'batch_delete' && $ids) {
        $ph = implode(',', array_fill(0, count($ids), '?'));
        foreach (db_all("SELECT * FROM $T WHERE id IN ($ph)", array_values($ids)) as $row) {
            yk_delete_upload_files(yk_article_upload_paths($row));
        }
        db_exec("DELETE FROM $T WHERE id IN ($ph)", array_values($ids));
        admin_log('批量删除文章', 'ID:' . implode(',', $ids));
        flash_set('已删除 ' . count($ids) . ' 篇文章');
    } elseif ($do === 'batch_move' && $ids) {
        $colId = (int)(isset($_POST['move_col']) ? $_POST['move_col'] : 0);
        $ph = implode(',', array_fill(0, count($ids), '?'));
        $args = array_merge(array($colId), array_values($ids));
        db_exec("UPDATE $T SET col_id = ? WHERE id IN ($ph)", $args);
        admin_log('批量移动文章', 'ID:' . implode(',', $ids) . ' 移至栏目:' . $colId);
        flash_set('已移动 ' . count($ids) . ' 篇文章');
    } else {
        flash_set('请先勾选文章', 'err');
    }
    header('Location: index.php' . (!empty($_GET['col']) ? '?col=' . (int)$_GET['col'] : ''));
    exit;
}

// ---------- 列表 ----------
$colId = (int)(isset($_GET['col']) ? $_GET['col'] : 0);
$page  = max(1, (int)(isset($_GET['p']) ? $_GET['p'] : 1));
$pageSize = 15;

$where = 'WHERE 1=1';
$args = array();
if ($colId > 0) {
    $where .= ' AND col_id = ?';
    $args[] = $colId;
}
$total = (int)db_val("SELECT COUNT(*) FROM $T $where", $args);
$start = ($page - 1) * $pageSize;
$list = db_all("SELECT * FROM $T $where ORDER BY is_top DESC, sort ASC, id DESC LIMIT $start, $pageSize", $args);

// 栏目名映射
$colNames = array();
foreach (db_all('SELECT id, name FROM ' . DB_PREFIX . 'column') as $c) {
    $colNames[$c['id']] = $c['name'];
}
$colOptions = column_options();

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3>文章列表 <a class="yk-btn sm" href="edit.php" style="float:right">+ 发布文章</a></h3>
  <form method="get" action="index.php" style="margin-bottom:14px">
    按栏目筛选：
    <select name="col" onchange="this.form.submit()">
      <option value="0">全部栏目</option>
      <?php foreach ($colOptions as $o): ?>
      <option value="<?php echo (int)$o['id']; ?>"<?php echo $colId === (int)$o['id'] ? ' selected' : ''; ?>><?php echo str_repeat('　', $o['depth']) . e($o['name']); ?></option>
      <?php endforeach; ?>
    </select>
    <span style="color:#999;font-size:12px;margin-left:10px">共 <?php echo $total; ?> 篇</span>
  </form>
  <form method="post" action="index.php<?php echo $colId ? '?col=' . $colId : ''; ?>">
    <?php echo csrf_field(); ?>
    <table class="yk-table">
      <tr>
        <th width="34"><input type="checkbox" onclick="var c=this.checked;document.querySelectorAll('.yk-ids').forEach(function(b){b.checked=c;})"></th>
        <th width="50">ID</th><th>标题</th><th width="70">封面</th><th width="110">所属栏目</th>
        <th width="50">置顶</th><th width="50">推荐</th><th width="60">浏览</th><th width="60">排序</th><th width="110" style="white-space:nowrap">发布时间</th><th width="60">状态</th><th width="150" style="white-space:nowrap">操作</th>
      </tr>
      <?php foreach ($list as $a): ?>
      <tr>
        <td><input type="checkbox" class="yk-ids" name="ids[]" value="<?php echo (int)$a['id']; ?>"></td>
        <td><?php echo (int)$a['id']; ?></td>
        <td class="yk-ed" data-id="<?php echo (int)$a['id']; ?>" data-field="title" title="双击快速修改"><?php echo e($a['title']); ?></td>
        <td><?php if (!empty($a['thumb'])) { ?><img src="<?php echo e(SITE_URL . '/' . ltrim($a['thumb'], '/')); ?>" style="width:52px;height:36px;object-fit:cover;border-radius:4px;border:1px solid #eef1f5" title="<?php echo e($a['thumb']); ?>"><?php } else { ?><span style="color:#bbb;font-size:12px">无封面</span><?php } ?></td>
        <td><?php echo isset($colNames[$a['col_id']]) ? e($colNames[$a['col_id']]) : '<span style="color:#999">未分类</span>'; ?></td>
        <td><?php echo $a['is_top'] ? '√' : ''; ?></td>
        <td><?php echo $a['is_recommend'] ? '√' : ''; ?></td>
        <td class="yk-ed" data-id="<?php echo (int)$a['id']; ?>" data-field="views" title="双击快速修改"><?php echo (int)$a['views']; ?></td>
        <td class="yk-ed" data-id="<?php echo (int)$a['id']; ?>" data-field="sort" title="双击快速修改"><?php echo (int)$a['sort']; ?></td>
        <td style="white-space:nowrap"><?php echo e(fdate($a['add_time'])); ?></td>
        <td><?php echo $a['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); ?>/?art=<?php echo (int)$a['id']; ?>" target="_blank">预览</a>
          <a href="edit.php?id=<?php echo (int)$a['id']; ?>">编辑</a>
          <button type="submit" name="do" value="delete_one" onclick="this.form.id.value=<?php echo (int)$a['id']; ?>;return confirm('确定删除该文章？');" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$list): ?><tr><td colspan="12" style="text-align:center;color:#999">暂无文章</td></tr><?php endif; ?>
    </table>
    <input type="hidden" name="id" value="0">
    <div style="margin-top:14px">
      <button class="yk-btn red sm" type="submit" name="do" value="batch_delete" onclick="return confirm('确定删除勾选的文章？');">批量删除</button>
      &nbsp;移动到栏目：
      <select name="move_col">
        <option value="0">未分类</option>
        <?php foreach ($colOptions as $o): ?>
        <option value="<?php echo (int)$o['id']; ?>"><?php echo str_repeat('　', $o['depth']) . e($o['name']); ?></option>
        <?php endforeach; ?>
      </select>
      <button class="yk-btn gray sm" type="submit" name="do" value="batch_move">批量移动</button>
    </div>
  </form>
  <?php echo admin_pager($total, $page, $pageSize, 'index.php' . ($colId ? '?col=' . $colId : '')); ?>
</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') === 'title' ? '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');
            fd.append('id', td.getAttribute('data-id'));
            fd.append('field', td.getAttribute('data-field'));
            fd.append('value', v);
            fetch('index.php<?php echo $colId ? '?col=' . $colId : ''; ?>', {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'; ?>
