<?php
namespace App\Helpers;

use ImageResize;
// use phpDocumentor\Reflection\File;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

/**
* Class based Helper to upload and resize Images
*/
class ImageHelper
{

    

    /**
     * Class based Helper to resize Images
     * @param $image file to resize, string
     * @param int $width
     * @param int $height
     * @return string to resized image url
     */
    public static function resize($image, $width= 200, $height= 200): string
    {
        if (preg_match('/https:\/\/img\.youtube\.com/', $image, $match) ) {
            return $image;
        }

        $image= public_path($image);
        if (! File::exists($image) ) {
            return asset('logo.png');
        }

        $imageInfo= pathinfo($image);

        $newFileName = $imageInfo['filename'].'-'.$width.'X'.$height.'.'.$imageInfo['extension'];

        // Resize image and upload to Thumbnail path
        // Thumbnail Path
        $upload_dir= '/uploads/images/thumbs';
        $destinationPath = public_path($upload_dir);
        // Save Image
        $img = ImageResize::make( $image );

        $img->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio(); // to save the ratio
        })->save($destinationPath.'/'.$newFileName);

        return asset($upload_dir.'/'.$newFileName);
    }

    /**
     * Class based Helper to Check if Image exist
     * @param $image file
     * @return string image url
     */
    public static function get( $image ): string
    {
        if(!$image) {
            return asset('logo.png');
        }

        if (preg_match('/https:\/\/img\.youtube\.com/', $image, $match) ) {
            return $image;
        }

        $imagePath= public_path($image);

        if (File::exists($imagePath)) {
            return asset($image);
        } else {
            return asset('logo.png');
        }
    }
}


