<?php

namespace Core;

class ImageProcessor
{
    public static function convertToWebP($sourcePath, $targetPath, $quality = 80)
    {
        $info = getimagesize($sourcePath);
        if (!$info) return false;

        $mime = $info['mime'];
        switch ($mime) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($sourcePath);
                imagepalettetotruecolor($image);
                imagealphablending($image, true);
                imagesavealpha($image, true);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($sourcePath);
                break;
            default:
                return false;
        }

        $result = imagewebp($image, $targetPath, $quality);
        imagedestroy($image);
        return $result;
    }

    public static function resize($sourcePath, $targetPath, $width, $height = null)
    {
        $info = getimagesize($sourcePath);
        if (!$info) return false;

        $origWidth = $info[0];
        $origHeight = $info[1];

        if ($height === null) {
            $height = floor($origHeight * ($width / $origWidth));
        }

        $mime = $info['mime'];
        switch ($mime) {
            case 'image/jpeg': $src = imagecreatefromjpeg($sourcePath); break;
            case 'image/png': $src = imagecreatefrompng($sourcePath); break;
            case 'image/gif': $src = imagecreatefromgif($sourcePath); break;
            default: return false;
        }

        $dst = imagecreatetruecolor($width, $height);
        
        if ($mime == 'image/png' || $mime == 'image/gif') {
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
        }

        imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $origWidth, $origHeight);

        switch ($mime) {
            case 'image/jpeg': imagejpeg($dst, $targetPath); break;
            case 'image/png': imagepng($dst, $targetPath); break;
            case 'image/gif': imagegif($dst, $targetPath); break;
        }

        imagedestroy($src);
        imagedestroy($dst);
        return true;
    }
}
