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

if (!function_exists('webp')) {

    function webp($sourceImage, $quality = 80)
    {
        $sourceImage = trim(ltrim($sourceImage, '.'), '/');
        if (strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false && 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);
                switch ($ext) {
                    case 'jpg':
                        $img = imagecreatefromjpeg($sourceImage);
                        break;
                    case 'png':
                        $img = imagecreatefrompng($sourceImage);
                        break;
                    default:
                        $img = null;
                        break;
                }
                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);
                }
            }

            return '/' . $webpFile;
        }

        return $sourceImage;
    }
}