<?php
namespace App\Controllers\Admin;

/**
 * 素材库：图片上传 / 列表 / 删除
 * 文件存于 public/assets/uploads，前后台通用（静态资源由框架直出）。
 */
class MediaController extends AdminController
{
    private function dir(): string
    {
        $d = BASE_PATH . '/public/assets/uploads';
        if (!is_dir($d)) mkdir($d, 0755, true);
        return $d;
    }

    /** 素材列表（JSON） GET admin/media */
    public function index()
    {
        header('Content-Type: application/json; charset=utf-8');
        $d = $this->dir();
        $items = [];
        foreach (glob($d . '/*.{jpg,jpeg,png,gif,webp,svg}', GLOB_BRACE) as $f) {
            $name = basename($f);
            $items[] = ['name' => $name, 'url' => site_url('assets/uploads/' . $name)];
        }
        echo json_encode(['items' => $items]);
    }

    /** 上传素材（JSON） POST admin/media/upload */
    public function upload()
    {
        header('Content-Type: application/json; charset=utf-8');
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_check()) {
            echo json_encode(['ok' => false, 'msg' => '请求无效']);
            return;
        }
        $path = $this->uploadFile('file');
        if (!$path) {
            echo json_encode(['ok' => false, 'msg' => '上传失败（仅支持 jpg/png/gif/webp/svg）']);
            return;
        }
        echo json_encode(['ok' => true, 'name' => basename($path), 'url' => site_url($path)]);
    }

    /** 删除素材 POST admin/media/delete/{name} 或 POST admin/media/delete + name 字段 */
    public function delete($name = null)
    {
        header('Content-Type: application/json; charset=utf-8');
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_check()) {
            echo json_encode(['ok' => false, 'msg' => '请求无效']);
            return;
        }
        $name = basename($name ?? ($_POST['name'] ?? ''));
        if ($name === '' || $name === '.' || $name === '..') {
            echo json_encode(['ok' => false, 'msg' => '参数缺失']);
            return;
        }
        $file = $this->dir() . '/' . $name;
        if (is_file($file) && @unlink($file)) {
            echo json_encode(['ok' => true]);
        } else {
            echo json_encode(['ok' => false, 'msg' => '删除失败']);
        }
    }
}
