<?php

namespace FiloBlu\Flow\Controller\Adminhtml\Category;

use Magento\Backend\App\Action;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class Export
 * @package FiloBlu\Flow\Controller\Adminhtml\Category
 */
class Export extends Action
{
    /**
     * @var PageFactory
     */
    public function execute()
    {
        $csv = "name;id;path\n\r";
        $response = $this->getResponse();
        $response->setHeader('Content-Description', 'Content-Description: File Transfer', true);
        $response->setHeader('Content-Type', 'application/octet-stream', true);
        $response->setHeader('Content-Disposition', 'attachment; filename=category.csv', true);
        $response->setHeader('Content-Transfer-Encoding', 'binary', true);
        $response->setHeader('Connection', 'Keep-Alive', true);

        $categoryCollection = ObjectManager::getInstance()
            ->get('\Magento\Catalog\Model\CategoryFactory')
            ->create()->getCollection();

        $categoryCollection->addAttributeToSelect(
            'name'
        )->addAttributeToSelect(
            'is_active'
        )->setStoreId(
            0
        );

        foreach ($categoryCollection as $category) {
            if ($category->getName()) {
                $csv_array[$category->getId()] = ["path" => $category->getPath(), "name" => $category->getName()];
            }
        }

        foreach ($csv_array as $key => $csv_item) {
            $text_path = '';
            $path = explode('/', $csv_item['path']);

            foreach ($path as $p_id) {
                if (isset($csv_array[$p_id]) && count($path) > 2) {
                    $text_path .= $csv_array[$p_id]['name'] . '/';
                }
            }

            $text_path = rtrim($text_path, '/');
            $csv .= $csv_item['name'] . ';' . $key . ';' . $text_path . "\n\r";
        }

        $response->setContent($csv);
    }
}
