<?php

namespace App\Helpers;

use Buglinjo\LaravelWebp\Webp;

class FileUploadHelper
{
    public static function uploadImage($image, $directory, $column_name, $avatar = false)
    {
        if ($image) {
            if ($column_name) {
                if (file_exists($column_name)) {
                    if ($column_name != 'storage/dummy.webp' || $column_name != 'storage/profile/avatar.webp') {
                        unlink($column_name);
                    }
                }
            }
            $slug = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($image->getClientOriginalName())));
            $imageName = $slug.'-'.time().'.webp';
            $imgURL = $directory.$imageName;
            Webp::make($image)->save($imgURL);
        } else {
            if ($column_name) {
                $imgURL = $column_name;
            } else {
                if ($avatar) {
                    $imgURL = 'storage/profile/avatar.webp';
                } else {
                    $imgURL = 'storage/dummy.webp';
                }
            }
        }

        return $imgURL;
    }
}
