<?php

namespace Nexus\Catalog\Controller\Adminhtml\Productlink;

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\CatalogProductLinkFactory $catalogProductLinkFactory,
        \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->productRepository = $productRepository;
        $this->_catalogProductLink = $catalogProductLinkFactory;
        parent::__construct($context);
    }

    /**
     * run the action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {



         $resultPage = $this->_catalogProductLink->create();
        $collection = $resultPage->getCollection();

        

        // echo "<pre>";
        // var_dump($collection->getData());
        // exit;


        $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) {
                  $cp = $this->_catalogProductLink->create(); 
                  $product_sku = $this->productRepository->get($value[0])->getId();
                  $linked_product_sku = $this->productRepository->get($value[1])->getId();
                  $link_type_id = $value[2];
                  $action = $value[3];
                  $collection =  $cp->getCollection()->addFieldToFilter('product_id',$product_sku)->addFieldToFilter('linked_product_id', $linked_product_sku)->addFieldToFilter('link_type_id',$link_type_id);               
                    if($collection->getSize()){
                        foreach ($collection as $item) {
                            if($action){continue;}
                            $item->delete();
                            $itemsDeleted++;
                        }
                      
                    }else{
                       if($action){ 

                            $cp->setData('product_id',$product_sku);
                            $cp->setData('linked_product_id',$linked_product_sku);
                            $cp->setData('link_type_id',$link_type_id);
                            $cp->save();
                            $newcsvrecords++;  
                        } 
                    }  

                

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

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

}
