<?php

namespace App\Services;

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

class ImageService
{
    /**
     * Compress and convert image to WebP
     */
    public static function uploadAndOptimize(UploadedFile $file, $folder = 'uploads')
    {
        $name = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $fileName = $name . '_' . time() . '.webp';
        $path = $folder . '/' . $fileName;

        // Load image based on type
        $image = null;
        $extension = $file->getClientOriginalExtension();

        switch (strtolower($extension)) {
            case 'jpeg':
            case 'jpg':
                $image = imagecreatefromjpeg($file->getRealPath());
                break;
            case 'png':
                $image = imagecreatefrompng($file->getRealPath());
                // Preserve transparency
                imagepalettetobruecolor($image);
                imagealphablending($image, true);
                imagesavealpha($image, true);
                break;
            case 'webp':
                $image = imagecreatefromwebp($file->getRealPath());
                break;
            default:
                // If not supported, just store as is
                return $file->store($folder, 'public');
        }

        // Optimization & WebP conversion
        // Create a temp file path
        $tempPath = tempnam(sys_get_temp_dir(), 'img');
        imagewebp($image, $tempPath, 80); // 80 quality
        imagedestroy($image);

        // Upload to storage
        Storage::disk('public')->put($path, file_get_contents($tempPath));
        unlink($tempPath);

        return $path;
    }
}
