<?php

namespace FiloBlu\Rma\Controller\Adminhtml\System;

use Exception;
use FiloBlu\Rma\Block\Adminhtml\Carrier\Matrixrate\ChangeSizeGrid;
use Magento\Backend\App\Action\Context;
use Magento\Config\Controller\Adminhtml\System\AbstractConfig;
use Magento\Config\Controller\Adminhtml\System\ConfigSectionChecker;
use Magento\Config\Model\Config\Structure;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class ExportChangeSizeMatrixrates extends AbstractConfig
{
    /**
     * @var FileFactory
     */
    protected $fileFactory;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param Context $context
     * @param Structure $configStructure
     * @param ConfigSectionChecker $sectionChecker
     * @param FileFactory $fileFactory
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        Structure $configStructure,
        ConfigSectionChecker $sectionChecker,
        FileFactory $fileFactory,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context, $configStructure, $sectionChecker);
        $this->storeManager = $storeManager;
        $this->fileFactory = $fileFactory;
    }

    /**
     * @return ResponseInterface
     * @throws LocalizedException
     * @throws Exception
     */
    public function execute()
    {
        $fileName = 'changesize_matrixrates.csv';
        /** @var ChangeSizeGrid $gridBlock */
        $gridBlock = $this->_view->getLayout()->createBlock(ChangeSizeGrid::class);
        $website = $this->storeManager->getWebsite($this->getRequest()->getParam('website'));

        if ($this->getRequest()->getParam('conditionName')) {
            $conditionName = $this->getRequest()->getParam('conditionName');
        } else {
            $conditionName = $website->getConfig('carriers/matrixrate/condition_name');
        }
        $gridBlock->setWebsiteId($website->getId())->setConditionName($conditionName);
        $content = $gridBlock->getCsvFile();
        return $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);
    }
}

