<?php
namespace Banyo\CustomProduct\Controller\Adminhtml\Brand;

use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\File\UploaderFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;

class LogoUpload extends Action
{
    protected $resultJsonFactory;
    protected $uploaderFactory;
    protected $filesystem;

    public function __construct(
        Action\Context $context,
        JsonFactory $resultJsonFactory,
        UploaderFactory $uploaderFactory,
        Filesystem $filesystem
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->uploaderFactory = $uploaderFactory;
        $this->filesystem = $filesystem;
    }

    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();

        try {
            $uploader = $this->uploaderFactory->create(['fileId' => 'brand_product_page_logo']);
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'svg']);
            $uploader->setAllowRenameFiles(true);

            $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $result = $uploader->save($mediaDirectory->getAbsolutePath('brand/logo/'));

            $mediaUrl = $this->_url->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]);
            return $resultJson->setData([
                'name' => $result['file'],
                'type' => $result['type'],
                'size' => $result['size'],
                'url' => $mediaUrl . 'brand/logo/' . $result['file'],
                'error' => false,
            ]);
        } catch (\Exception $e) {
            return $resultJson->setData([
                'error' => true,
                'message' => $e->getMessage(),
            ]);
        }
    }
}
