<?php
// 临时增加内存限制，防止大图处理崩溃
@ini_set('memory_limit', '256M');

// 定义常量
define('UPLOAD_DIR', dirname(dirname(__FILE__)) . '/images/upload');
define('MAX_WIDTH', 1280);       // 最大宽度
define('MAX_SIZE', 1024 * 1024); // 最大大小：1MB
define('IMAGE_QUALITY', 85);     // 压缩质量

// 统一返回JSON
function response($code, $msg = '', $data = []) {
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8');
    }
    echo json_encode([
        'code' => $code,
        'msg'  => $msg,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 检查并创建上传目录
if (!is_dir(UPLOAD_DIR)) {
    if (!mkdir(UPLOAD_DIR, 0755, true)) {
        response(1, '上传目录创建失败，请检查权限');
    }
}

// 检查文件
if (empty($_FILES) || empty($_FILES['file'])) {
    response(1, '请选择要上传的文件');
}

$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
    $errorMsg = [
        UPLOAD_ERR_INI_SIZE => '文件超过php.ini限制',
        UPLOAD_ERR_FORM_SIZE => '文件超过表单限制',
        UPLOAD_ERR_PARTIAL => '文件仅部分上传',
        UPLOAD_ERR_NO_FILE => '未上传文件',
        UPLOAD_ERR_NO_TMP_DIR => '缺少临时目录',
        UPLOAD_ERR_CANT_WRITE => '写入失败',
        UPLOAD_ERR_EXTENSION => '上传被中断'
    ];
    $msg = isset($errorMsg[$file['error']]) ? $errorMsg[$file['error']] : '文件上传失败';
    response(1, $msg);
}

$tempFile = $file['tmp_name'];
$fileParts = pathinfo($file['name']);
$extension = strtolower($fileParts['extension']); 
$allowedExts = ['jpg', 'jpeg', 'gif', 'png'];     

if (!in_array($extension, $allowedExts)) {
    response(1, '不支持的文件类型');
}

// 生成文件名 (先按原后缀生成，如果需要转JPG后面会改)
$newFileName = time() . rand(11111, 55555) . '.' . $extension;
$targetFile = rtrim(UPLOAD_DIR, '/') . '/' . $newFileName;

$imageInfo = @getimagesize($tempFile);
if (!$imageInfo) {
    response(1, '不是有效的图片');
}
$width = $imageInfo[0];
$height = $imageInfo[1];
$fileSize = $file['size'];

// 判断是否需要压缩
$needCompress = ($width > MAX_WIDTH) || ($fileSize > MAX_SIZE);

if ($needCompress) {
    function compressImage($source, $dest, $extension, $maxWidth, $maxSize, $quality) {
        $srcImage = null;
        $finalExtension = $extension;

        // 1. 创建图片资源
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                $srcImage = @imagecreatefromjpeg($source);
                break;
            case 'png':
                $srcImage = @imagecreatefrompng($source);
                // 【核心修改】如果是PNG且需要压缩，直接标记转为JPG
                $finalExtension = 'jpg'; 
                break;
            case 'gif':
                $srcImage = @imagecreatefromgif($source);
                // GIF 转 JPG 也通常是为了压缩，这里一并处理
                $finalExtension = 'jpg';
                break;
            default:
                return false;
        }

        if (!$srcImage) return false;

        // 2. 修复手机拍照翻转 (仅针对原图是JPG的情况)
        if (in_array($extension, ['jpg', 'jpeg']) && function_exists('exif_read_data')) {
            $exif = @exif_read_data($source);
            if ($exif !== false && !empty($exif['Orientation'])) {
                $orientation = (int)$exif['Orientation'];
                if ($orientation == 3) $srcImage = @imagerotate($srcImage, 180, 0);
                elseif ($orientation == 6) $srcImage = @imagerotate($srcImage, -90, 0);
                elseif ($orientation == 8) $srcImage = @imagerotate($srcImage, 90, 0);
                if (!$srcImage) {
                    // 旋转失败重试加载
                    if ($extension === 'jpg' || $extension === 'jpeg') {
                        $srcImage = @imagecreatefromjpeg($source);
                    }
                    if(!$srcImage) return false;
                }
            }
        }

        // 3. 计算新尺寸
        $srcWidth = imagesx($srcImage);
        $srcHeight = imagesy($srcImage);

        if ($srcWidth > $maxWidth) {
            $newWidth = $maxWidth;
            $newHeight = (int)($srcHeight * ($newWidth / $srcWidth));
        } else {
            $newWidth = $srcWidth;
            $newHeight = $srcHeight;
        }

        // 4. 创建画布 (因为最终都要转JPG，所以统一用白色背景填充)
        $newImage = imagecreatetruecolor($newWidth, $newHeight);
        $white = imagecolorallocate($newImage, 255, 255, 255);
        imagefill($newImage, 0, 0, $white);

        imagecopyresampled(
            $newImage, $srcImage,
            0, 0, 0, 0,
            $newWidth, $newHeight,
            $srcWidth, $srcHeight
        );

        imagedestroy($srcImage); // 释放原图

        // 5. 循环压缩直到满足大小 (只针对JPG输出)
        $currentQuality = $quality;
        $attempts = 0;
        $tempCompressFile = null;

        do {
            $tempCompressFile = @tempnam(sys_get_temp_dir(), 'img_compress_');
            if (!$tempCompressFile) {
                imagedestroy($newImage);
                return false;
            }

            // 统一输出为 JPG
            $saveResult = @imagejpeg($newImage, $tempCompressFile, $currentQuality);

            if (!$saveResult) {
                @unlink($tempCompressFile);
                imagedestroy($newImage);
                return false;
            }

            $compressedSize = @filesize($tempCompressFile);
            if ($compressedSize === false) $compressedSize = 0;

            // 如果满足大小或尝试次数过多，停止
            if ($compressedSize <= $maxSize || $attempts >= 5) {
                break;
            }

            // 降低质量重试
            $currentQuality -= 5;
            $currentQuality = max(10, $currentQuality);
            $attempts++;
            
            @unlink($tempCompressFile); // 删除本次不满意的临时文件

        } while (true);

        // 6. 如果格式变了（PNG->JPG），修改目标路径后缀
        if ($finalExtension !== $extension) {
            $dest = preg_replace('/\.' . $extension . '$/i', '.jpg', $dest);
        }

        // 移动文件
        if ($tempCompressFile && file_exists($tempCompressFile)) {
            if (!@rename($tempCompressFile, $dest)) {
                if (!@copy($tempCompressFile, $dest)) {
                    @unlink($tempCompressFile);
                    imagedestroy($newImage);
                    return false;
                }
                @unlink($tempCompressFile);
            }
        } else {
            imagedestroy($newImage);
            return false;
        }

        imagedestroy($newImage);
        return true;
    }

    if (!compressImage($tempFile, $targetFile, $extension, MAX_WIDTH, MAX_SIZE, IMAGE_QUALITY)) {
        response(1, '图片压缩失败');
    }

    // 更新返回的文件名（如果后缀被函数内部修改了）
    // 简单方法：重新扫描该时间戳开头的文件
    $baseName = pathinfo($newFileName, PATHINFO_FILENAME);
    $actualFiles = glob(rtrim(UPLOAD_DIR, '/') . '/' . $baseName . '.*');
    if (!empty($actualFiles)) {
        $newFileName = basename($actualFiles[0]);
    }

} else {
    // 不需要压缩，直接移动
    if (!@move_uploaded_file($tempFile, $targetFile)) {
        response(1, '文件保存失败');
    }
}

response(0, '上传成功', ['src' => $newFileName]);
?>