<?php

namespace App\Libs\Services;

use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpKernel\Exception\HttpException;

class FileService
{
    public function storeFile($data)
    {
        if ($data['fileType'] === 'image') {
            $destinationPath = config('path.internal.temp');
        } else if ($data['fileType'] === 'public') {
            $destinationPath = config('path.internal.media_documents_temp');
        } else {
            $destinationPath = config('path.private.temp');
        }

        $extension = $data['file']->getClientOriginalExtension();
        $originalFilename  = pathinfo($data['file']->getClientOriginalName(), PATHINFO_FILENAME);
        $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $originalFilename);
        $newFilename = urlize($withoutExt);
        $tempFinalName = $newFilename .'.'.$extension;
        //Checks for colliding filenames
        $i = 1;

        while (Storage::has($destinationPath.'/'.$tempFinalName)) {
            $tempFinalName = $newFilename .'-'.$i.'.'.$extension;
            $i++;
            //for safety
            if ($i > 200) {
                throw new HttpException(400, 'The uploaded file already exists');
            }
        }

        $data['file']->storeAs($destinationPath, $tempFinalName);
        $fileUrl = config('app.url') . Storage::url($destinationPath . '/' . $tempFinalName);

        return [
            'finalName' => $tempFinalName,
            'fileUrl' => $fileUrl,
        ];
    }
}
