<?php
namespace App\Classes\Service;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class Base64Uploader
{
    public function execute(string $base64Image, string $path) {
        
        if($base64Image !== ''){
            
            $type = $this->getFileType($base64Image);
            
            $extension = $this->getExtension($base64Image, $type);
            
            $uniqueName = uniqid('img_').time();
            
            $imagePath = $path.'/'.$uniqueName.'.'.$extension;
            
            $encodedExtension = $extension;
            
            if($extension === 'xlsx'){
                $encodedExtension = 'vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            }
            $data = base64_decode(str_replace(' ', '+', str_replace('data:'.$type.'/'.$encodedExtension.';base64,', '', $base64Image)));
            
            Storage::disk('public')->put($imagePath, $data);
            
            return $uniqueName.'.'.$extension;
            
        }
        
    }
    
    private function getFileType(string $base64Image){
        return explode('/', explode(':', substr($base64Image, 0, strpos($base64Image, ';')))[1])[0];
    }
    
    private function getExtension(string $base64Image, string $type) {
        $extension = explode('/', explode(':', substr($base64Image, 0, strpos($base64Image, ';')))[1])[1];
        
        if($extension === 'vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
            return 'xlsx';
        }
        
        return $extension;
    }
}