<?php
namespace App\Services;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ImageOptimizerService {
    public function storeWebp(UploadedFile $file, string $directory='images', int $maxWidth=1920, int $quality=82): string {
        if (!extension_loaded('gd')) return $file->store($directory,'public');
        $mime=$file->getMimeType();
        $image=match($mime){'image/jpeg'=>imagecreatefromjpeg($file->getRealPath()),'image/png'=>imagecreatefrompng($file->getRealPath()),'image/webp'=>imagecreatefromwebp($file->getRealPath()),default=>null};
        if (!$image) return $file->store($directory,'public');
        $w=imagesx($image); $h=imagesy($image); $newW=min($w,$maxWidth); $newH=(int)round($h*($newW/$w));
        $canvas=imagecreatetruecolor($newW,$newH);
        imagealphablending($canvas,false); imagesavealpha($canvas,true);
        imagecopyresampled($canvas,$image,0,0,0,0,$newW,$newH,$w,$h);
        $name=Str::slug(pathinfo($file->getClientOriginalName(),PATHINFO_FILENAME)).'-'.Str::lower(Str::random(6)).'.webp';
        $tmp=tempnam(sys_get_temp_dir(),'nutugu_'); imagewebp($canvas,$tmp,$quality);
        Storage::disk('public')->put($directory.'/'.$name,file_get_contents($tmp));
        @unlink($tmp); imagedestroy($image); imagedestroy($canvas);
        return $directory.'/'.$name;
    }
}
