<?php

namespace Nexus\Catalog\Controller\Adminhtml\Categoryimport;

use Magento\Backend\App\Action;
use Magento\Framework\File\Csv;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Nexus\Catalog\Model\CategoryPositionFactory;

class ImportLists extends Action
{
    /**
     * @var \Magento\Backend\Model\Session
     */
    protected $_backendSession;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var \Magento\Backend\Model\View\Result\RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;

    /**
     * @var \Magento\Framework\Filesystem\Directory\WriteInterface
     */
    protected $_mediaDirectory;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    protected $_fileUploaderFactory;

    /**
     * @var \Magento\Framework\File\Csv
     */
    protected $csv;

    /**
     * @var \Nexus\Catalog\Model\CategoryPositionFactory
     */
    protected $_categoryPosition;

    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Model\Session $backendSession
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Backend\Model\View\Result\RedirectFactory $resultRedirectFactory
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
     * @param \Nexus\Catalog\Model\CategoryPositionFactory $categoryPositionFactory
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param \Magento\Framework\File\Csv $csv
     */
    public function __construct(
        \Magento\Backend\Model\Session $backendSession,
        \Magento\Framework\Registry $registry,
        \Magento\Backend\Model\View\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Backend\App\Action\Context $context,
        Filesystem $filesystem,
        UploaderFactory $fileUploaderFactory,
        CategoryPositionFactory $categoryPositionFactory,
        ProductRepositoryInterface $productRepository,
        Csv $csv
    ) {
        $this->_backendSession = $backendSession;
        $this->_registry = $registry;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->_filesystem = $filesystem;
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->_categoryPosition = $categoryPositionFactory;
        $this->productRepository = $productRepository;
        $this->csv = $csv;

        parent::__construct($context);
    }

    /**
     * Execute the action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $data = $this->getRequest()->getFiles();
        $filename = $data['file']['name'] ?? null;
        $extension = $filename ? pathinfo($filename, PATHINFO_EXTENSION) : null;

        $resultRedirect = $this->resultRedirectFactory->create();

        if (!isset($data['file']['tmp_name'])) {
            $this->messageManager->addError(__("Invalid file upload attempt."));
            $resultRedirect->setPath('*/categoryimport/import');
            return $resultRedirect;
        }

        try {
            $csvData = $this->csv->getData($data['file']['tmp_name']);
            $header = $csvData[0];
            array_shift($csvData);

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
            $connection = $resource->getConnection();
            $connection->query("SET FOREIGN_KEY_CHECKS=0;");

            $itemsPosition = 0;
            $itemsDeleted = 0;
            $newcsvrecords = 0;

            foreach ($csvData as $key => $value) {
                $cp = $this->_categoryPosition->create();
                $categoryId = $value[0];
                $productId = $this->productRepository->get($value[1])->getId();
                $position = $value[2];
                $action = $value[3];

                $collection = $cp->getCollection()
                    ->addFieldToFilter('category_id', $categoryId)
                    ->addFieldToFilter('product_id', $productId);

                if ($collection->getSize()) {
                    foreach ($collection as $item) {
                        if ($action) {
                            $item->setData('position', $position)->save();
                            $itemsPosition++;
                        } else {
                            $item->delete();
                            $itemsDeleted++;
                        }
                    }
                } else {
                    if ($action) {
                        $cp->setData('category_id', $categoryId);
                        $cp->setData('product_id', $productId);
                        $cp->setData('position', $position);
                        $cp->save();
                        $newcsvrecords++;
                    }
                }
            }

            $connection->query("SET FOREIGN_KEY_CHECKS=1;");
            $this->messageManager->addSuccess(__("Import has been successfully finished."));
            if ($itemsPosition) {
                $this->messageManager->addSuccess(__("Total $itemsPosition products' positions have been updated."));
            }
            if ($itemsDeleted) {
                $this->messageManager->addSuccess(__("Total $itemsDeleted products have been deleted."));
            }
            if ($newcsvrecords) {
                $this->messageManager->addSuccess(__("Total $newcsvrecords products have been linked to categories."));
            }

            $resultRedirect->setPath('*/categoryimport/import');
            return $resultRedirect;

        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
            $resultRedirect->setPath('*/categoryimport/import');
            return $resultRedirect;
        }
    }
}

// namespace Nexus\Catalog\Controller\Adminhtml\Categoryimport;

// class ImportLists extends \Magento\Backend\App\Action
// {
//     protected $_backendSession;
 
//     protected $_storeManager;

//     public function __construct(
//         \Magento\Backend\Model\Session $backendSession,      
//         \Magento\Framework\Registry $registry,
//         \Magento\Backend\Model\View\Result\RedirectFactory $resultRedirectFactory,
//         \Magento\Backend\App\Action\Context $context,       
// 		\Magento\Framework\Filesystem $filesystem,       
// 		\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
//         \Nexus\Catalog\Model\CategoryPositionFactory $categoryPositionFactory,
//         \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
//         \Magento\Framework\File\Csv $csv
//     )
//     {
//         $this->_backendSession = $backendSession;
//         $this->context = $context;      
//         $this->_filesystem = $filesystem;       
// 		$this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
// 		$this->_fileUploaderFactory = $fileUploaderFactory;		
//         $this->csv = $csv;
//         $this->_categoryPosition = $categoryPositionFactory;
//         $this->productRepository = $productRepository;
//         parent::__construct($context);
//     }

//     /**
//      * run the action
//      *
//      * @return \Magento\Backend\Model\View\Result\Redirect
//      */
//     public function execute()
//     {
//         $data = $this->getRequest()->getFiles();
//         $filename = $data['file']['name'];
//         $extension = pathinfo($filename, PATHINFO_EXTENSION);
        
//         $resultRedirect = $this->resultRedirectFactory->create();
                  
//         if (!isset($data['file']['tmp_name'])){ 
      
//             $this->messageManager->addError(__("Invalid file upload attempt."));
//             $resultRedirect->setPath('*/categoryimport/import');
//             return $resultRedirect;        
//         }
        
//         try {        

//             $csvData = $this->csv->getData($data['file']['tmp_name']);
//             $header= $csvData[0];
//             array_shift($csvData);
//             $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//             $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
//             $connection = $resource->getConnection();
//             $connection->query("SET FOREIGN_KEY_CHECKS=0;");           
//             $itemsPosition = 0;
//             $itemsDeleted = 0;
//             $newcsvrecords = 0;      
                 
//             foreach ($csvData as $key => $value) {
//                /* if(empty($value[0]) || empty($value[2]) || empty($value[1]) || empty($value[3])){
//                     $row = $key;
//                     $this->messageManager->addError(__("Please add values in Row ".$row));
//                     continue;
//                 }*/
//                    $cp = $this->_categoryPosition->create();
//                    $categoryid =  $value[0];
//                    $product_id = $this->productRepository->get($value[1])->getId();
//                    $position =  $value[2];
//                    $action =  $value[3];
//                    $collection =  $cp->getCollection()->addFieldToFilter('category_id',$categoryid)->addFieldToFilter('product_id',$product_id);
//                     if($collection->getSize()){
//                         foreach ($collection as $item) {
//                             if($action){                               
//                                $item->setData('position',$position)->save(); 
//                                $itemsPosition++; 
//                             }else{
//                                 $item->delete();
//                                 $itemsDeleted++;
//                             }
                            
//                         }
                       

//                     }else{
//                         if($action){
//                             $cp->setData('category_id',$categoryid);
//                             $cp->setData('product_id',$product_id);
//                             $cp->setData('position',$position);
//                             $cp->save();
//                             $newcsvrecords++;  
//                         } 


//                     }   
               

//             }      
         
            
// 			$connection->query("SET FOREIGN_KEY_CHECKS=1;");
//             $this->messageManager->addSuccess(__("Import has been successfully finished."));
//             if($itemsPosition){
//                 $this->messageManager->addSuccess(__("Total $itemsPosition products position has been updated."));
//             }
//             if($itemsDeleted){
//                 $this->messageManager->addSuccess(__("Total $itemsDeleted products  has been deleted."));
//             }
//              if($newcsvrecords){
//                 $this->messageManager->addSuccess(__("Total $newcsvrecords products  has been linked to categories."));
//             }
			
//             $resultRedirect->setPath('*/categoryimport/import');
            
// 			return $resultRedirect;

// 		} catch (\Exception $e) {
// 			$this->messageManager->addError(__($e->getMessage()));
// 			$resultRedirect->setPath('*/categoryimport/import');
// 			return $resultRedirect;
// 		}
		
//     }

// }
