<?php
/**
 * 图片上传接口
 */
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json');

// 检查是否登录
if (!isLoggedIn()) {
    echo json_encode(['error' => '请先登录']);
    exit;
}

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

$file = $_FILES['image'];

// 检查文件类型
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['error' => '只支持 JPG、PNG、GIF、WebP 格式的图片']);
    exit;
}

// 限制文件大小 (最大 5MB)
$maxSize = 5 * 1024 * 1024; // 5MB
if ($file['size'] > $maxSize) {
    echo json_encode(['error' => '图片大小不能超过 5MB']);
    exit;
}

// 创建上传目录
$uploadDir = __DIR__ . '/../uploads/images/' . date('Y/m');
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

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

// 移动上传的文件
if (move_uploaded_file($file['tmp_name'], $filepath)) {
    // 如果图片太大，进行压缩
    $imageInfo = getimagesize($filepath);
    if ($imageInfo) {
        $maxWidth = 1920;
        $maxHeight = 1080;
        
        list($width, $height) = $imageInfo;
        
        // 如果图片尺寸超过限制，进行压缩
        if ($width > $maxWidth || $height > $maxHeight) {
            compressImage($filepath, $filepath, $maxWidth, $maxHeight);
        }
    }
    
    $url = SITE_URL . '/uploads/images/' . date('Y/m') . '/' . $filename;
    echo json_encode(['url' => $url]);
} else {
    echo json_encode(['error' => '保存文件失败']);
}

/**
 * 压缩图片
 */
function compressImage($source, $destination, $maxWidth, $maxHeight) {
    $info = getimagesize($source);
    $width = $info[0];
    $height = $info[1];
    $type = $info[2];
    
    // 计算新尺寸
    $ratio = min($maxWidth / $width, $maxHeight / $height);
    $newWidth = $width * $ratio;
    $newHeight = $height * $ratio;
    
    // 创建新图像
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // 根据类型加载原图
    switch ($type) {
        case IMAGETYPE_JPEG:
            $sourceImage = imagecreatefromjpeg($source);
            break;
        case IMAGETYPE_PNG:
            $sourceImage = imagecreatefrompng($source);
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
            break;
        case IMAGETYPE_GIF:
            $sourceImage = imagecreatefromgif($source);
            break;
        case IMAGETYPE_WEBP:
            $sourceImage = imagecreatefromwebp($source);
            break;
        default:
            return false;
    }
    
    // 缩放图片
    imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    // 保存图片
    switch ($type) {
        case IMAGETYPE_JPEG:
            imagejpeg($newImage, $destination, 85);
            break;
        case IMAGETYPE_PNG:
            imagepng($newImage, $destination, 8);
            break;
        case IMAGETYPE_GIF:
            imagegif($newImage, $destination);
            break;
        case IMAGETYPE_WEBP:
            imagewebp($newImage, $destination, 85);
            break;
    }
    
    imagedestroy($newImage);
    imagedestroy($sourceImage);
    
    return true;
}
