<?php
/**
 * @category Mageants_SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) Mageants
 * @author Mageants
 */

declare(strict_types=1);

namespace Mageants\SimpleConfigurable\Controller\Adminhtml\Export;

use Magento\Backend\App\Action\Context;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\Result\Raw;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Component\ComponentRegistrar;

class Download extends Action
{
    /**
     * Module name
     */
    private const MODULE_NAME = 'Mageants_SimpleConfigurable';

    /**
     * @var FileFactory
     */
    protected $fileFactory;

    /**
     * @var RawFactory
     */
    protected $resultRawFactory;

    /**
     * @var ComponentRegistrar
     */
    protected $componentRegistrar;

    /**
     * Constructor
     */
    public function __construct(
        Context $context,
        FileFactory $fileFactory,
        RawFactory $resultRawFactory,
        ComponentRegistrar $componentRegistrar
    ) {
        parent::__construct($context);
        $this->fileFactory = $fileFactory;
        $this->resultRawFactory = $resultRawFactory;
        $this->componentRegistrar = $componentRegistrar;
    }

    /**
     * Check permission
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Mageants_SimpleConfigurable::export');
    }

    /**
     * Download file from module files/ directory
     */
    public function execute()
    {
        $fileName = 'scppreselectimport.csv'; // static filename (or use request param if dynamic)

        // Get full path to the module directory
        $moduleDir = $this->componentRegistrar->getPath(
            ComponentRegistrar::MODULE,
            self::MODULE_NAME
        );

        $filePath = $moduleDir . '/files/' . $fileName;
        // Check if file exists
        if (!file_exists($filePath)) {
            $this->messageManager->addErrorMessage(__('The file does not exist.'));
            return $this->getResultRedirect();
        }

        $fileContents = file_get_contents($filePath);
        $fileSize = filesize($filePath);

        $this->fileFactory->create(
            $fileName,
            null,
            DirectoryList::VAR_DIR,
            'application/octet-stream',
            $fileSize
        );

        /** @var Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        $resultRaw->setContents($fileContents);
        $resultRaw->setHeader('Content-Type', 'application/octet-stream', true);
        $resultRaw->setHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"', true);
        $resultRaw->setHeader('Content-Length', (string)$fileSize, true);

        return $resultRaw;
    }

    /**
     * Redirect helper
     */
    private function getResultRedirect(): Redirect
    {
        return $this->resultRedirectFactory->create()->setPath('*/export/index');
    }
}
