<?php
/**
 * @category Mageants ConfigurablePreselect
 * @package Mageants_ConfigurablePreselect
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */

namespace Mageants\SimpleConfigurable\Controller\Adminhtml\System\Config;

use Magento\Backend\App\Action\Context;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Action;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Filesystem\Driver\File as DriverInterface;

class Import extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\App\Request\Http
     */
    protected $_request;

    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $_productRepository;

    /**
     * @var \Magento\Catalog\Model\Product\Action
     */
    protected $_productActionObject;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $_resultJsonFactory;

    /**
     * @var DriverInterface
     */
    protected $driverInterface;

    /**
     * Get
     *
     * @param Context $context
     * @param Http $request
     * @param ProductRepository $productRepository
     * @param Action $productActionObject
     * @param JsonFactory $resultJsonFactory
     * @param DriverInterface $driverInterface
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Catalog\Model\Product\Action $productActionObject,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        DriverInterface $driverInterface
    ) {
        $this->_request = $request;
        $this->_productRepository = $productRepository;
        $this->_productActionObject = $productActionObject;
        $this->_resultJsonFactory = $resultJsonFactory;
        $this->driverInterface = $driverInterface;
        parent::__construct($context);
    }

    /**
     * ResponseInterface
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $csvFile = $this->_request->getFiles('preselectcsvfile');
        $result = $this->_resultJsonFactory->create();

        $csvFile = $this->driverInterface->fileOpen($csvFile['tmp_name'], 'r');

        $csvheader = $this->driverInterface->fileGetCsv($csvFile);
        $header1 = "configurable product sku";
        $header2 = "associated product sku";
        $errormessage = "";
        $isimportable = 0;
        $multierrormessage[] = ["Row No.","configurable product sku","associated product sku","Mesasge"];
        $rownum = 1;
        $importedrow = 0;
        $resultmessage = [];

        if (count($csvheader)==2) {
            if (trim($csvheader[0])==$header1 && trim($csvheader[1])==$header2) {
                $isimportable = 1;
            } else {
                $errormessage = "Column headers not match with standard csv format.";
            }
        } else {
            $errormessage = "Number of column not match with standard csv format.";
        }

        // Parse data from CSV file line by line
        if ($isimportable==1 && $errormessage=="") {
            while (($line = $this->driverInterface->fileGetCsv($csvFile)) !== false) {
                $confsku = trim($line[0]);
                $assosku = trim($line[1]);
                $isimported = 0;

                $configurableproduct = $this->getProductBySku($confsku);

                if ($configurableproduct) {
                    $_children = $configurableproduct->getTypeInstance()->getUsedProducts($configurableproduct);
                    foreach ($_children as $child) {
                        if ($assosku==$child->getSku()) {
                            $array_product = [$configurableproduct->getId()];
                            $this->_productActionObject
                                ->updateAttributes($array_product, ['is_default_selected' => $child->getId()], 0);
                            $isimported = 1;
                            $importedrow++;
                            break;
                        }
                    }

                    if ($isimported==0) {
                        $multierrormessage[] = [$rownum,$confsku,$assosku,"Associated product with sku" .
                            $assosku . " is not associated with configurable product with sku " . $confsku];
                    }
                } else {
                    $multierrormessage[] = [$rownum,$confsku,$assosku,"Configurable product with sku" .
                        $confsku . " does not exist"];
                }

                $rownum++;
            }

            $resultmessage = ["success"=>"Import csv successfully with row " .
                $importedrow . " out of " . ($rownum-1),"multierror"=>$multierrormessage];
        } else {
            $resultmessage = ["error"=>$errormessage];
        }

        return $result->setData($resultmessage);
    }

    /**
     * Check Permission.
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return true;
    }

    /**
     * GetProductBySku
     *
     * @param string $sku
     * @return ProductInterface|Product|string
     */
    public function getProductBySku($sku)
    {
        try {
            return $this->_productRepository->get($sku);
        } catch (\Exception $ex) {
            return "";
        }
    }
}
