<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('webp')) {

    function webp($sourceImage, $quality = 80)
    {
        $sourceImage = trim(ltrim($sourceImage, '.'), '/');
        if (str_contains((string)$_SERVER['HTTP_ACCEPT'], 'image/webp') && file_exists($sourceImage)) {
            $filePath = 'assets/uploads/cropped/webp/' . trim(pathinfo($sourceImage, PATHINFO_DIRNAME), '/');
            if (!file_exists($filePath)) {
                if (!mkdir($filePath, 0775, true)) {
                    show_error('Can\'t create folder `' . $filePath . '`');
                }
            }
            $webpFile = $filePath . '/' . pathinfo($sourceImage, PATHINFO_FILENAME) . '.webp';
            if (!file_exists($webpFile)) {
                $ext = pathinfo($sourceImage, PATHINFO_EXTENSION);
                $img = match ($ext) {
                    'jpg', 'jpeg' => imagecreatefromjpeg($sourceImage),
                    'png' => imagecreatefrompng($sourceImage),
                    default => null,
                };
                if (!is_null($img)) {
                    $w = imagesx($img);
                    $h = imagesy($img);
                    $webp = imagecreatetruecolor($w, $h);
                    imagecopy($webp, $img, 0, 0, 0, 0, $w, $h);
                    imagewebp($webp, $webpFile, $quality);
                    imagedestroy($img);
                    imagedestroy($webp);
                } else {
                    return $sourceImage;
                }
            }
            return '/' . $webpFile;
        }

        return $sourceImage;
    }
}