<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

trait ImageHandler
{
    /**
     * 將圖片轉換為 WebP 並儲存
     *
     * @param UploadedFile $file 原始檔案
     * @param string $directory 儲存目錄 (不含 disk 名稱)
     * @param int $quality 壓縮品質 (0-100)
     * @return string 儲存的路徑
     */
    protected function storeAsWebp(UploadedFile $file, string $directory, int $quality = 80): string
    {
        $filename = Str::random(40) . '.webp';
        $path = "{$directory}/{$filename}";

        // 讀取原始圖片資訊
        $imageInfo = getimagesize($file->getRealPath());
        if (!$imageInfo) {
            return $file->store($directory, 'public');
        }

        $mime = $imageInfo['mime'];
        $source = null;

        switch ($mime) {
            case 'image/jpeg':
                $source = imagecreatefromjpeg($file->getRealPath());
                break;
            case 'image/png':
                $source = imagecreatefrompng($file->getRealPath());
                break;
            case 'image/gif':
                $source = imagecreatefromgif($file->getRealPath());
                break;
            case 'image/webp':
                $source = imagecreatefromwebp($file->getRealPath());
                break;
            default:
                // 不支援的格式直接存
                return $file->store($directory, 'public');
        }

        if (!$source) {
            return $file->store($directory, 'public');
        }

        // 確保支援真彩色 (解決 palette image 問題)
        if (!imageistruecolor($source)) {
            imagepalettetotruecolor($source);
        }

        // 確保目錄存在
        Storage::disk('public')->makeDirectory($directory);
        $fullPath = Storage::disk('public')->path($path);

        // 轉換並儲存
        imagewebp($source, $fullPath, $quality);
        imagedestroy($source);

        return $path;
    }
}
