<?php

namespace App\Services;

use App\Models\ProductManagement\Product;
use App\Traits\ImageUploadTrait;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;

class ImageService{
    use ImageUploadTrait;

    /**
     * @param $images
     * @param Product $product
     * @param int $i
     */
    public function storeProductImages($images,Product $product, $i = 1){
        foreach ($images as $image) {
            $product->media()->create([
                'file_name' => $this->uploadImages($product->name, $image, $i, 'products', 500, NULL),
                'file_size' => $image->getSize(),
                'file_type' => $image->getMimeType(),
                'file_status' => true,
                'file_sort' => $i
            ]);

            $i++;
        }
    }

    /**
     * @param $fileName
     * @param $image
     * @return string
     */
    public function storeUserImages($fileName, $image): string{
        return $this->uploadImage(
            $fileName,
            $image,
            'users',
            300,
            NULL
        );
    }

    /**
     * @param $image
     * @param $folderName
     */
    public function unlinkImage($image, $folderName){
        if (File::exists('storage/images/'. $folderName .'/' . $image)) {
            unlink('storage/images/'. $folderName .'/' . $image);
        }
    }

    public function resize(UploadedFile $file,$width = NULL, $height = NULL){
        $image_name = $file->getClientOriginalName();
        $path = public_path($image_name);
         Image::make($file->getRealPath())
                    ->resize($width, $height, function ($constraint) {
                        $constraint->aspectRatio();
                    })
                   ->save($path, 100)
            ;

         return $path;
    }
}
