<?php
    /*
            *****************************************************************************
            * MEGA Digital Space - by MEGA Digital Studio                               *
            * ------------------------------------------------------------------------- *
            * CMS Website:  https://megadigital.space                                   *
            * License:  https://megadigital.space/license                               *
            * Owner:  Giorgi Basharuli                                                  *
            * Contact:  online@megadigital.studio                                       *
            * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
            * Website:  https://megadigital.studio                                      *
            * ------------------------------------------------------------------------- *
            * Description: This file is a part of the MEGA Digital Space CMS system.    *
            * Unauthorized distribution, modification, or commercial use is strictly -  *
            * prohibited without prior written permission.                              *
            * ------------------------------------------------------------------------- *
            * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
            * All rights reserved.                                                      *
            *****************************************************************************
        */

    function autoOptimizeWebP($sourcePath, $destinationPath = null, $maxWidth = 0, $maxHeight = 0) {
        if (!file_exists($sourcePath)) return false;

        $info = getimagesize($sourcePath);
        if (!$info) return false;

        $mime = $info['mime'];
        $width = $info[0];
        $height = $info[1];

        // Создаём изображение из исходника
        switch ($mime) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($sourcePath);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($sourcePath);
                break;
            case 'image/webp':
                $image = imagecreatefromwebp($sourcePath);
                break;
            default:
                return false;
        }

        // Масштабирование, если нужно
        if (($maxWidth > 0 && $width > $maxWidth) || ($maxHeight > 0 && $height > $maxHeight)) {
            $ratio = $width / $height;

            if ($maxWidth > 0 && $width > $maxWidth) {
                $newWidth = $maxWidth;
                $newHeight = round($maxWidth / $ratio);
            } else {
                $newWidth = $width;
                $newHeight = $height;
            }

            if ($maxHeight > 0 && $newHeight > $maxHeight) {
                $newHeight = $maxHeight;
                $newWidth = round($maxHeight * $ratio);
            }

            $newImage = imagecreatetruecolor($newWidth, $newHeight);

            // Сохраняем прозрачность для PNG/GIF
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);

            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
            imagedestroy($image);
            $image = $newImage;
        }

        // Путь к WebP
        if (!$destinationPath) {
            $destinationPath = preg_replace('/\.(jpe?g|png|gif|webp)$/i', '.webp', $sourcePath);
        }

        // Авто-оптимизация качества: пробуем с 85, уменьшаем до 75 если файл > 500KB
        $quality = 85;
        imagewebp($image, $destinationPath, $quality);
        $filesize = filesize($destinationPath);

        if ($filesize > 500 * 1024) { // если больше 500KB
            $quality = 75;
            imagewebp($image, $destinationPath, $quality);
        }

        // Если всё ещё большой, уменьшаем до 65
        $filesize = filesize($destinationPath);
        if ($filesize > 500 * 1024) {
            $quality = 65;
            imagewebp($image, $destinationPath, $quality);
        }

        imagedestroy($image);
        return $destinationPath;
    }

