<?php

namespace App\Traits;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use function League\Flysystem\Local\directoryExists;

trait ImageUploadTrait{
    protected string $path  = 'app/public/images/';

    /**
     * @param $name
     * @param $img
     * @param $folderName
     * @param null $image_width
     * @param null $image_height
     * @return string
     */
    public function uploadImage($name, $img, $folderName, $image_width = NULL, $image_height = NULL){
        $image_name = $this->imageName($name, $img);
        $disk = Storage::disk("public");

        if($disk->exists($folderName)){
            $disk->makeDirectory($folderName);
        }

        $realPath = $this->path.$folderName;

        if (!file_exists(storage_path($realPath))) {
            mkdir(storage_path($realPath), 0755, true);
        }

        Image::make($img->getRealPath())
              ->resize($image_width, $image_height, function ($constraint) {
                    $constraint->aspectRatio();
              })->save(storage_path($this->path.$folderName.'/'.$image_name), 100);

        return $image_name;
    }

    /**
     * @param $name
     * @param $img
     * @param $i
     * @param $folderName
     * @param null $image_width
     * @param null $image_height
     * @return string
     */
    public function uploadImages($name, $img, $i, $folderName, $image_width = NULL, $image_height = NULL){
        $image_name = $this->randomImageName($name, $img, $i);

        $base_path = storage_path($this->path.$folderName);
        if (!file_exists($base_path)) {
            mkdir($base_path, 0755, true);
        }
        Image::make($img->getRealPath())
            ->resize($image_width, $image_height, function ($constraint) {
                $constraint->aspectRatio();
            })->save("$base_path/$image_name", 100);

        return $image_name;
    }

    /**
     * @param $imageName
     * @param $image
     * @return string
     */
    protected function imageName($imageName, $image){
        return Str::slug($imageName) . '.' . $image->getClientOriginalExtension();
    }

    /**
     * @param $imageName
     * @param $image
     * @param $i
     * @return string
     */
    protected function randomImageName($imageName, $image, $i){
        return Str::slug($imageName) . time() . '-' . $i . '.' . $image->getClientOriginalExtension();
    }
}
