<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use InvalidArgumentException;
use RuntimeException;

trait Base64ToFile
{
    /**
     * Convert a base64 string to a file
     *
     * @param  string  $base64String  The base64 encoded string
     * @param  string  $fileName  Optional filename (without extension)
     *
     * @throws InvalidArgumentException If the base64 string is invalid
     * @throws RuntimeException If file creation fails
     */
    protected function convertBase64ToFile(string $base64String, ?string $fileName = null): UploadedFile
    {
        if (! preg_match('/^data:([^;]+);base64,(.+)$/', $base64String, $matches)) {
            throw new InvalidArgumentException('Invalid base64 string format');
        }

        $mimeType      = data_get($matches, 1);
        $base64Content = data_get($matches, 2);

        $fileContent = base64_decode($base64Content, true);

        if ($fileContent === false) {
            throw new InvalidArgumentException('Failed to decode base64 content');
        }

        $extension = $this->getExtensionFromMimeType($mimeType);

        $fileName     = $fileName ?? uniqid('file_', true);
        $fullFileName = "{$fileName}.{$extension}";

        $tempPath = sys_get_temp_dir().'/'.$fullFileName;

        if (file_put_contents($tempPath, $fileContent) === false) {
            throw new RuntimeException('Failed to create temporary file');
        }

        return new UploadedFile(
            $tempPath,
            $fullFileName,
            $mimeType,
            null,
            true
        );
    }

    /**
     * Get file extension from mime type
     */
    private function getExtensionFromMimeType(string $mimeType): string
    {
        $mimeToExt = [
            'image/jpeg'                                                              => 'jpg',
            'image/png'                                                               => 'png',
            'image/gif'                                                               => 'gif',
            'application/pdf'                                                         => 'pdf',
            'text/plain'                                                              => 'txt',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'       => 'xlsx',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
            'application/vnd.ms-excel'                                                => 'xls',
        ];

        return data_get($mimeToExt, $mimeType, 'bin');
    }
}
