<?php
/**
 * Magetop Store
 *
 * @category  Magetop Extensions
 * @package   Magetop_Quotesystem
 * @author    Magetop Developer
 * @copyright Copyright (c) Magetop (https://www.magetop.com)
 * @license   https://www.magetop.com/license.html
 */

namespace Magetop\Quotesystem\Controller\Adminhtml\Managequotes;

use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Json\Helper\Data as JsonHelper;

/**
 * Quotesystem Quote File Upload controller.
 */
class FileUpload extends Action
{
    /**
     * @var \Magento\Framework\Filesystem\Directory\WriteInterface
     */
    private $_mediaDirectory;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    private $_fileUploader;

    /**
     * @var JsonHelper
     */
    private $jsonHelper;

    /**
     * File Upload
     *
     * @param Action\Context                                   $context
     * @param Filesystem                                       $filesystem
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $fileUploader
     * @param JsonHelper                                       $jsonHelper
     * @param \Magetop\Quotesystem\Helper\Data                  $helper
     */
    public function __construct(
        Action\Context $context,
        Filesystem $filesystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploader,
        JsonHelper $jsonHelper,
        \Magetop\Quotesystem\Helper\Data $helper
    ) {
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(
            DirectoryList::MEDIA
        );
        $this->_fileUploader = $fileUploader;
        $this->jsonHelper = $jsonHelper;
        $this->helper = $helper;
        parent::__construct($context);
    }

    /**
     * Execute
     */
    public function execute()
    {
        try {
            $errors = $this->helper->validateFiles($this->getRequest()->getFiles());
            if (empty($errors)) {
                $target = $this->_mediaDirectory->getAbsolutePath('mtquote\files');
                $fileUploaderFactory = $this->_fileUploader->create(
                    ['fileId' => 'files']
                );
                $allowedTypes = $this->helper->getAllowedFileTypes();
                $allowedExtensions = [];
                if ($allowedTypes) {
                    $allowedExtensions = explode(',', $allowedTypes);
                }
                if (empty($allowedExtensions)) {
                    $allowedExtensions = ['gif', 'jpg', 'png', 'jpeg', 'pdf', 'doc', 'zip'];
                }
                $fileUploaderFactory->validateFile();
                $fileUploaderFactory->setAllowedExtensions(
                    $allowedExtensions
                );
                $fileUploaderFactory->setFilesDispersion(true);
                $fileUploaderFactory->setAllowRenameFiles(true);
                $fileResultData = $fileUploaderFactory->save($target);
                unset($fileResultData['tmp_name']);
                unset($fileResultData['path']);
                $fileResultData['extension'] = $fileResultData['file'];
                $this->getResponse()->representJson(
                    $this->jsonHelper->jsonEncode($fileResultData)
                );
            } else {
                foreach ($errors as $key => $errorMsg) {
                    $this->messageManager->addError($errorMsg);
                    $this->getResponse()->representJson(
                        $this->jsonHelper->jsonEncode(
                            [
                            'error' => $errorMsg,
                            'errorcode' => 1
                            ]
                        )
                    );
                }
            }
        } catch (\Exception $e) {
            $this->getResponse()->representJson(
                $this->jsonHelper->jsonEncode(
                    [
                        'error' => $e->getMessage(),
                        'errorcode' => $e->getCode(),
                    ]
                )
            );
        }
    }
}
