<?php
// 不需要再次启动会话，因为主index.php已经启动了
// session_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';

// 检查管理员权限
if (!isAdmin()) {
    http_response_code(403);
    echo json_encode(['error' => '权限不足']);
    exit;
}

// 检查是否有文件上传
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => '没有上传文件或上传失败']);
    exit;
}

$file = $_FILES['image'];

// 验证文件类型
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowed_types)) {
    http_response_code(400);
    echo json_encode(['error' => '不支持的文件类型']);
    exit;
}

// 验证文件大小（最大5MB）
if ($file['size'] > 5 * 1024 * 1024) {
    http_response_code(400);
    echo json_encode(['error' => '文件大小不能超过5MB']);
    exit;
}

// 创建上传目录
$upload_dir = UPLOADS_PATH . '/' . date('Y/m/d');
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// 生成文件名
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $extension;
$filepath = $upload_dir . '/' . $filename;

// 移动文件
if (move_uploaded_file($file['tmp_name'], $filepath)) {
    $url = '/uploads/' . date('Y/m/d') . '/' . $filename;
    echo json_encode(['url' => $url]);
} else {
    http_response_code(500);
    echo json_encode(['error' => '文件保存失败']);
}
?>