<?php

namespace Nexus\Catalog\Controller\Adminhtml\Frequantly;



use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Nexus\Catalog\Model\FrequantlyFactory;


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,
        FrequantlyFactory $FrequantlyFactory,
        \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->_frequantlyFactory = $FrequantlyFactory;
        $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('*/frequantly/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->_frequantlyFactory->create(); 
                    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
                    $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
                    $productObj = $productRepository->get($value[0]);
                    $product_sku = $productObj->getId();
                    $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
                    $linkOb = $productRepository->get($value[1]);
                    $linked_product_sku  = $linkOb->getId();

                    $action = $value[2];

                  $collection =  $cp->getCollection()->addFieldToFilter('product_id',$product_sku)->addFieldToFilter('linked_product_id', $linked_product_sku);               
                    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('*/frequantly/import');
            
            return $resultRedirect;

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

}
