<?php

namespace App\Traits;

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

trait UploadsBase64Image
{
    /**
     * Upload a base64 encoded image and return the URL.
     *
     * @throws \Exception
     */
    public function uploadBase64Image(string $base64Image, string $folder): string
    {
        // Extract the file extension and base64 data
        if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
            $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);

            $type = strtolower(data_get($type, 1)); // jpg, png, gif

            if (! in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                throw new Exception(__('validation.extensions', ['attribute' => __('general.image'), 'values' => 'jpg, jpeg, png, gif']));
            }

            $image = base64_decode($base64Image);

            if ($image === false) {
                throw new Exception('Base64 decode failed');
            }
        } else {
            throw new Exception('Invalid base64 image format');
        }

        // Generate a unique filename
        $filename = Str::random(20).'.'.$type;

        // Define the full path where the file will be stored
        $filePath = $folder.'/'.$filename;

        Storage::put($filePath, $image);

        return $filePath;
    }
}
