<?php
namespace Nexus\Catalog\Controller\Adminhtml\Category;
use Magento\Framework\App\Filesystem\DirectoryList;

class ExportCsv extends \Magento\Backend\App\Action {

    protected $resultPageFactory;
    protected $fileFactory;
    protected $directoryList;
    protected $csvWriter;
    protected $_categoryPosition;
    protected $_productFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Nexus\Catalog\Model\CategoryPositionFactory $categoryPositionFactory,
        \Magento\Framework\File\Csv $csvWriter,
        \Magento\Catalog\Model\ProductFactory $productFactory // ← ADD THIS
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->fileFactory       = $fileFactory;
        $this->directoryList     = $directoryList;
        $this->csvWriter         = $csvWriter;
        $this->_categoryPosition = $categoryPositionFactory;
        $this->_productFactory   = $productFactory; // ← ADD THIS
    }


    /**
     *
     * @return type
     */
    public function execute() {

        $fileName = 'categorycsv.csv';
        $result = $this->_categoryPosition->create()->getCollection()->addFieldToFilter('category_id',(int)$this->getRequest()->getParam('id', 0));
        $data = [];
        $data[]=['category_id','product_sku','position','action','title','price','stock_status'];
        if(count($result)){
            foreach ($result as  $item) {
                $productColletion = $this->_productFactory->create()->getCollection()->addFieldToFilter('entity_id',$item['product_id'])->addAttributeToSelect(
                'name')->addAttributeToSelect('sku')->addAttributeToSelect('price');
               $productColletion = $productColletion->setFlag('has_stock_status_filter', true);
                $productColletion = $productColletion
                ->joinField('qty',
                        'cataloginventory_stock_item',
                        'qty',
                        'product_id=entity_id',
                        '{{table}}.stock_id=1',
                        'left'
                    )->joinTable('cataloginventory_stock_item', 'product_id=entity_id', array('stock_status' => 'is_in_stock'))
                    ->addAttributeToSelect('stock_status')->load();





                $storeId = (int)$this->getRequest()->getParam('store', 0);

                if ($storeId > 0) {
                        $productColletion->addStoreFilter($storeId);
                }
                if($productColletion->getSize()){
                    $product = $productColletion->getFirstItem();

                    $data[]=[(int)$this->getRequest()->getParam('id', 0),$product->getSku(),$item['position'],'1',$product->getName(),number_format($product->getPrice(),2),$product->getStockStatus()];


                }
            }
        }
        if (count($data)) {
            $fileDirectory = \Magento\Framework\App\Filesystem\DirectoryList::MEDIA;
            $fileName = 'category_product_export_' . date('d-m-y H:i:s') . '.csv';

            $exportDir = $this->directoryList->getPath('var') . "/export";
            if (!is_dir($exportDir)) {
                mkdir($exportDir, 0775, true);
            }

            $filePath = $exportDir . "/" . $fileName;

            $this->csvWriter
                ->setEnclosure('"')
                ->setDelimiter(',')
                ->saveData($filePath, $data);

            return $this->fileFactory->create('export.csv', [
                'type'  => 'filename',
                'value' => $filePath,
                'rm'    => true,
            ], 'var');
        }


    }
}
