<?php

namespace App\Http\Helpers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class FileUploader
{

    public static function store(string $containingFolder, $file)
    {
        try{
            if(!$file ) {
                return null;
            }
            if(!$file->isValid()) {
                throw new \Exception('File is not valid');
            }
            $file->getClientOriginalExtension();
        
            if(isset($file->type)) {
                if($file->type == 'link') {
                    return $file->link;
                }
            }

            $str = $containingFolder . Str::random() . '.' . $file->getClientOriginalExtension();

            Storage::disk(env('UPLOAD_DISK'))->put($str, $file->getContent());

            return Storage::disk(env('UPLOAD_DISK'))->url($str);

        } catch (\Exception $e) {
            throw new \Exception('File is not valid');
        }
    }

    public static function delete($file)
    {
        Storage::disk(env('UPLOAD_DISK'))->delete($file);

        return;
    }

    public static function storeBase64(string $containingFolder, $file)
    {
        $extension = explode('/', explode(':', substr($file, 0, strpos($file, ';')))[1])[1];   // .jpg .png .pdf

        $replace = substr($file, 0, strpos($file, ',')+1);

       $image = str_replace($replace, '', $file);

       $image = str_replace(' ', '+', $image);

        $str = $containingFolder . Str::random() . '.' . $extension;

        Storage::disk(env('UPLOAD_DISK'))->put($str, base64_decode($image));

        return Storage::disk(env('UPLOAD_DISK'))->url($str);
    }

    public static function getFileType($file)
    {
        if(isset($file->type)) {
            if($file->type == 'link') {
                return 'link';
            }
        }
        return (substr($file->getMimeType(), 0, 5) == 'image') ? "image" : 'file';
    }
}
