<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


session_start();

// 检查登录
if (!isset($_SESSION['admin_id']) || empty($_SESSION['admin_id'])) {
    jsonResponse(['code' => 401, 'msg' => '未登录']);
}

require_once dirname(__DIR__) . '/core/db/db.php';

$action = $_GET['action'] ?? 'upload';

switch ($action) {
    case 'upload':
        uploadImage();
        break;
    case 'delete':
        deleteImage();
        break;
    default:
        jsonResponse(['code' => 400, 'msg' => '未知操作']);
}

function uploadImage() {
    // 获取上传的文件
    $file = $_FILES['file'] ?? null;
    
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        jsonResponse(['code' => 400, 'msg' => '请选择要上传的图片']);
    }
    
    // 检查文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        jsonResponse(['code' => 400, 'msg' => '仅支持 JPG、PNG、GIF、WebP 格式']);
    }
    
    // 检查文件大小 (最大 5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        jsonResponse(['code' => 400, 'msg' => '图片大小不能超过 5MB']);
    }
    
    // 创建上传目录
    $uploadDir = dirname(__DIR__) . '/public/uploads/' . date('Ymd') . '/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // 生成文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('img_') . '.' . $ext;
    $filepath = $uploadDir . $filename;
    
    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        $url = '/public/uploads/' . date('Ymd') . '/' . $filename;
        jsonResponse([
            'code' => 0,
            'msg' => '上传成功',
            'data' => [
                'url' => $url,
                'filename' => $filename
            ]
        ]);
    } else {
        jsonResponse(['code' => 500, 'msg' => '文件保存失败']);
    }
}

function deleteImage() {
    $url = $_POST['url'] ?? '';
    if (empty($url)) {
        jsonResponse(['code' => 400, 'msg' => '缺少文件路径']);
    }
    
    $filepath = dirname(__DIR__) . $url;
    if (file_exists($filepath)) {
        unlink($filepath);
        jsonResponse(['code' => 0, 'msg' => '删除成功']);
    } else {
        jsonResponse(['code' => 404, 'msg' => '文件不存在']);
    }
}

function jsonResponse($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}