<?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\Filesystem\Driver\File as DriverFile;
use Magento\Framework\Json\Helper\Data as JsonHelper;

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

    /**
     * @var DriverFile
     */
    private $driverFiles;

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

    /**
     * File Delete
     *
     * @param Action\Context $context
     * @param Filesystem     $filesystems
     * @param DriverFile     $driverFiles
     * @param JsonHelper     $jsonHelper
     * @codeCoverageIgnore
     */
    public function __construct(
        Action\Context $context,
        Filesystem $filesystems,
        DriverFile $driverFiles,
        JsonHelper $jsonHelper
    ) {
        $this->_mediaDirectory = $filesystems->getDirectoryWrite(
            DirectoryList::MEDIA
        );
        $this->driverFiles = $driverFiles;
        $this->jsonHelper = $jsonHelper;
        parent::__construct($context);
    }

    /**
     * Execute
     */
    public function execute()
    {
        try {
            $fileName = $this->getRequest()->getParam('file_name');
            $target = $this->_mediaDirectory->getAbsolutePath('mtquote\files');
            $resultData['error'] = 1;
            if ($this->driverFiles->isExists($target.$fileName)) {
                $this->driverFiles->deleteFile($target.$fileName);
                $resultData['error'] = 0;
            }
            $this->getResponse()->representJson(
                $this->jsonHelper->jsonEncode($resultData)
            );
        } catch (\Exception $e) {
            $this->getResponse()->representJson(
                $this->jsonHelper->jsonEncode(
                    [
                        'error' => $e->getMessage(),
                        'errorcode' => $e->getCode(),
                    ]
                )
            );
        }
    }
}
