<?php
/**
 * 炎酷CMS - 素材管理（上传/分类筛选/网格列表/删除）
 * 上传走 api/upload.php（JS fetch）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';

$page_title = '素材管理';
$active = 'upload';
$T = DB_PREFIX . 'upload';

// ---------- 删除 ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    if ((isset($_POST['do']) ? $_POST['do'] : '') === 'delete') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $row = db_one("SELECT * FROM $T WHERE id = ?", array($id));
        if ($row) {
            db_exec("DELETE FROM $T WHERE id = ?", array($id));
            // 删除物理文件（仅允许 public/uploads/ 目录内）
            $uploadRoot = realpath(SITE_PATH . '/public/uploads');
            $filePath   = realpath(SITE_PATH . '/public/' . ltrim($row['filepath'], '/'));
            if ($uploadRoot && $filePath && strpos($filePath, $uploadRoot) === 0 && is_file($filePath)) {
                @unlink($filePath);
            }
            admin_log('删除素材', 'ID:' . $id . ' 文件:' . $row['filepath']);
            flash_set('素材已删除');
        }
    }
    header('Location: index.php' . (!empty($_GET['cat']) ? '?cat=' . urlencode($_GET['cat']) : ''));
    exit;
}

// ---------- 列表 ----------
$cat = isset($_GET['cat']) ? trim($_GET['cat']) : '';
$where = 'WHERE 1=1';
$args = array();
if ($cat !== '') {
    $where .= ' AND category = ?';
    $args[] = $cat;
}
$list = db_all("SELECT * FROM $T $where ORDER BY id DESC LIMIT 200", $args);
$cats = db_all("SELECT DISTINCT category FROM $T ORDER BY category");
$isImgExt = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'ico', 'svg');

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3>上传素材</h3>
  <form class="yk-form" id="ykUpForm" onsubmit="return ykDoUpload();">
    <div class="row"><label>选择文件</label><div class="ipt"><input type="file" id="ykFile"><div class="tip">允许后缀：<?php echo e(site_config('upload_ext')); ?>；大小不超过 <?php echo e(site_config('upload_max', '2')); ?> MB</div></div></div>
    <div class="row"><label>分类</label><div class="ipt">
      <input type="text" id="ykCat" list="ykCats" value="<?php echo e($cat !== '' ? $cat : '默认'); ?>" style="max-width:200px">
      <datalist id="ykCats"><?php foreach ($cats as $c): ?><option value="<?php echo e($c['category']); ?>"><?php endforeach; ?></datalist>
    </div></div>
    <div class="row"><label></label><div class="ipt">
      <button class="yk-btn" type="submit" id="ykUpBtn">上传</button>
      <span id="ykUpMsg" style="margin-left:10px;color:#999"></span>
    </div></div>
  </form>
</div>

<div class="yk-card">
  <h3>素材列表</h3>
  <div style="margin-bottom:14px">
    分类筛选：
    <a href="index.php"<?php echo $cat === '' ? ' style="font-weight:bold"' : ''; ?>>全部</a>
    <?php foreach ($cats as $c): ?>
    &nbsp;|&nbsp;<a href="index.php?cat=<?php echo urlencode($c['category']); ?>"<?php echo $cat === $c['category'] ? ' style="font-weight:bold"' : ''; ?>><?php echo e($c['category']); ?></a>
    <?php endforeach; ?>
  </div>
  <div class="yk-grid">
    <?php foreach ($list as $u):
      $ext = strtolower(pathinfo($u['filepath'], PATHINFO_EXTENSION));
      $isImg = in_array($ext, $isImgExt);
    ?>
    <div class="cell">
      <?php if ($isImg): ?>
      <img src="<?php echo e(SITE_URL . '/' . ltrim($u['filepath'], '/')); ?>" alt="">
      <?php else: ?>
      <div style="height:90px;line-height:90px;background:#f0f2f5;border-radius:4px;color:#999"><?php echo e(strtoupper($ext)); ?> 文件</div>
      <?php endif; ?>
      <div class="nm" title="<?php echo e($u['filepath']); ?>"><?php echo e($u['filepath']); ?></div>
      <div style="font-size:12px;color:#999"><?php echo e($u['category']); ?> · <?php echo e(number_format($u['filesize'] / 1024, 1)); ?>KB</div>
      <div style="margin-top:6px">
        <a href="javascript:;" onclick="ykCopy('<?php echo e($u['filepath']); ?>')">复制路径</a>
        <form method="post" action="index.php<?php echo $cat !== '' ? '?cat=' . urlencode($cat) : ''; ?>" 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)$u['id']; ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
      </div>
    </div>
    <?php endforeach; ?>
    <?php if (!$list): ?><p style="color:#999">暂无素材</p><?php endif; ?>
  </div>
</div>
<script>
var YK_UP_API = <?php echo json_encode(SITE_URL . '/api/upload.php'); ?>;
var YK_CSRF = <?php echo json_encode(csrf_token()); ?>;
function ykDoUpload(){
  var f = document.getElementById('ykFile');
  var msg = document.getElementById('ykUpMsg');
  if(!f.files || !f.files.length){ msg.textContent='请先选择文件'; return false; }
  var fd = new FormData();
  fd.append('file', f.files[0]);
  fd.append('category', document.getElementById('ykCat').value || '默认');
  fd.append('csrf_token', YK_CSRF);
  var btn = document.getElementById('ykUpBtn');
  btn.disabled = true; msg.textContent = '上传中…';
  var x = new XMLHttpRequest();
  x.open('POST', YK_UP_API, true);
  x.onreadystatechange = function(){
    if(x.readyState === 4){
      btn.disabled = false;
      try{
        var r = JSON.parse(x.responseText);
        if(r.code === 0){
          msg.textContent = '上传成功：' + r.data.path;
          setTimeout(function(){ location.reload(); }, 600);
        }else{
          msg.textContent = '失败：' + r.msg;
        }
      }catch(e){ msg.textContent = '上传失败，请重试'; }
    }
  };
  x.send(fd);
  return false;
}
function ykCopy(path){
  if(navigator.clipboard && navigator.clipboard.writeText){
    navigator.clipboard.writeText(path).then(function(){ alert('已复制：' + path); });
  }else{
    prompt('复制以下路径：', path);
  }
}
</script>
<?php require dirname(__DIR__) . '/inc/footer.php'; ?>
