<?php
/**
 * Created by PhpStorm.
 * User: MUHAMMAD fahad AHMAD
 * Date: 2/19/2019
 * Time: 10:06 AM
 */

namespace App\Services\Admin;

use App\Exceptions\ApiCustomException;
use App\libs\Response\GlobalApiResponseCodeBook;
use App\Services\BaseService;
use App\Models\TempPublicImage;
use Illuminate\Http\UploadedFile;

class UploadFileService extends BaseService
{
    /**
     * @param $user
     * @param UploadedFile $uploadedFile
     * @param string $name
     * @param string $publicFolderPath
     * @return TempPublicImage
     * @throws ApiCustomException
     */
    public function uploadPublicFile(UploadedFile $uploadedFile, string $name, string $publicFolderPath)
    {
        try {
            if (!empty($publicFolderPath)) $publicFolderPath = 'storage/' . $publicFolderPath;
            return $this->getPublicImage($name, $uploadedFile, $publicFolderPath);
        } catch (\Exception $exception) {
            throw new ApiCustomException('Something went wrong please try again later.', GlobalApiResponseCodeBook::INTERNAL_SERVER_ERROR);
        }
    }

    public function uploadPublicFiles($uploadedFiles, string $name, string $publicFolderPath)
    {
        try {
            $uploadedFilesArray = [];
            if (!empty($publicFolderPath)) $publicFolderPath = 'storage/' . $publicFolderPath;
            foreach ($uploadedFiles as $uploadedFile) {
                $tempPublicImage = $this->getPublicImage($name, $uploadedFile, $publicFolderPath);
                $uploadedFilesArray[] = $tempPublicImage;
            }
            return $uploadedFilesArray;
        } catch (\Exception $exception) {
            throw new ApiCustomException('Something went wrong please try again later.', GlobalApiResponseCodeBook::INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * @param string $name
     * @param $uploadedFile
     * @param string $publicFolderPath
     * @return TempPublicImage
     */
    public function getPublicImage(string $name, $uploadedFile, string $publicFolderPath): TempPublicImage
    {
        if (!empty($name)) $name = $name . '_' . rand(10000, 99999) . rand(1000, 9999);
        $extension = $uploadedFile->getClientOriginalExtension() ?: 'jpg';
        $name = $name . '.' . $extension;
        $uploadedFile->move(public_path($publicFolderPath), $name);
        $tempPublicImage = new TempPublicImage();
        $tempPublicImage->path = "$publicFolderPath/$name";
        $tempPublicImage->save();
        return $tempPublicImage;
    }
}
