<?php

namespace Webkul\WebkulCsvBundle\Connector\ArrayConverter\StandardToFlat;

use Webkul\WebkulCsvBundle\Classes\Magento2Class;
use Webkul\WebkulCsvBundle\Classes\ProductCustomType;
use Webkul\WebkulCsvBundle\DataFormatter\BaseFormater;
use Webkul\WebkulCsvBundle\Entity\TemplateConfiguration;
use Webkul\WebkulCsvBundle\Services\WebkulCsvConnector;

$classLoader = new \Webkul\WebkulCsvBundle\Listener\ClassDefinationForCompatibility();
$classLoader->customLoaderSystem();

class Product extends BaseFormater implements \ArrayConverterInterface
{
    /** @var ConnectorService */
    protected $connectorService;
    
    /** @var TemplateConfiguration */
    protected $templateStore = null;
    
    /** @var array */
    protected $multiRow = [];

    /** @var array */
    protected $magentoConfigurationVariations = [];

    /** @var array */
    protected $productCustomHeaders = [];

    /** @var array */
    protected $storeTemplateData = [];

    /** @var array */
    protected $variantAxesField = [];

    /** @var string */
    protected $storeName;

    /** @var string */
    protected $storeTmpName;

    /** @var ProductCustomType */
    protected $productCustomType;

    /** @var Magento2Class */
    protected $magento2ClassObject;

    /** @var ShopifyClass */
    protected $shopifyClassObject;

    /** @var array */
    protected $headers = [];

    /** @var string */
    protected $locale;

    /** @var array */
    protected $extraMapping = [];

    /** @var bool */
    protected $withHeader = false;

    public $stepExecution;

    /** @var string */
    protected $categoriesSeperator;
    
    /** @var string */
    protected $csvCategoryDelimeter;

    /** @var string */
    protected $variantFormatSeperator;

    /** @var string */
    protected $productFormatSeperator;

    /** @var string */
    protected $multiValueSeperator;

    /** @var string */
    protected $exportRootCategory;

    /** @var string */
    protected $exportSelectOptionLabel;

    /** @var string */
    protected $exportMetricUnit;

    /** @var string */
    protected $exportAttributeLabel;

    /** @var string */
    protected $exportCategoryLabel;
    
    /** @var array */
    protected $attributesCodeByTypes;

    /** @var array */
    public $multipleImageField = [];

    /**
     * @param WebkulCsvConnector $connectorService
     */
    public function __construct(WebkulCsvConnector $connectorService)
    {
        $this->connectorService = $connectorService;
    }

    /**
      * {@inheritdoc}
      */
    public function initializeRequirements()
    {
        $parameters                   = $this->stepExecution->getJobParameters()->all();
        $this->templateStore          = $this->connectorService->getTemplateStore($parameters['exportProfile']);
        $storeTemplateData            = json_decode($this->templateStore->getRawValues(), true);
        $storeTemplateData            = isset($storeTemplateData['csvExportMapping']) ? $storeTemplateData['csvExportMapping'] : [];
        $this->storeTemplateData      = isset($storeTemplateData['rawValues']) ? $storeTemplateData['rawValues']: [];
        $this->extraMapping           = isset($storeTemplateData['extraMapping']) ? $storeTemplateData['extraMapping'] : [];
        $this->variantFormatSeperator = !empty($this->extraMapping['variantFormatSeperator']) ? $this->extraMapping['variantFormatSeperator'] : '=';
        $this->productFormatSeperator = !empty($this->extraMapping['productFormatSeperator']) ? $this->extraMapping['productFormatSeperator'] : '=';
        $this->multiValueSeperator    = !empty($this->extraMapping['multiValueSeperator']) ? $this->extraMapping['multiValueSeperator'] : ',';
        $this->exportRootCategory     = !empty($this->extraMapping['exportRootCategory']) ? $this->extraMapping['exportRootCategory'] : 'false';
        $this->exportSelectOptionLabel = !empty($this->extraMapping['exportSelectOptionLabel']) ? $this->extraMapping['exportSelectOptionLabel'] : 'false';
        $this->exportMetricUnit       = !empty($this->extraMapping['exportMetricUnit']) ? $this->extraMapping['exportMetricUnit'] : 'false';
        $this->exportAttributeLabel   = !empty($this->extraMapping['exportAttributeLabel']) ? $this->extraMapping['exportAttributeLabel'] : 'false';
        $this->exportCategoryLabel    = !empty($this->extraMapping['exportCategoryLabel']) ? $this->extraMapping['exportCategoryLabel'] : 'false';
        $this->storeName              = $this->templateStore->getName();
        $this->storeTmpName           = 'wk_akeneo_'. strtolower($this->storeName) .'_csv_export';
        $this->variantAxesField       = isset($storeTemplateData['variantAxesField']) ? $storeTemplateData['variantAxesField'] : [];
        $this->locale                 = isset($parameters['filters']['structure']['locale']) ? reset($parameters['filters']['structure']['locale']) : '';
        $this->currency               = $parameters['filters']['structure']['currency'];
        $this->categoriesSeperator    = $parameters['WebkulCsvCategorySeperator'] ? $parameters['WebkulCsvCategorySeperator'] : ',';
        $this->csvCategoryDelimeter   = $parameters['WebkulCsvCategoryDelimeter'] ? $parameters['WebkulCsvCategoryDelimeter'] : ',';
        $this->magento2ClassObject    = new Magento2Class();
        $this->productCustomType      = new ProductCustomType();
        $this->productCustomHeaders   = $this->productCustomType->customProductTypeHeaders;
        $this->attributeCodeByTypes   = $this->getAttributeCodeByType();
        $this->headers   = array_keys($this->storeTemplateData);

        if (!empty($this->extraMapping['enabledFieldName'])) {
            if ($pos = array_search($this->extraMapping['enabledFieldName'], $this->headers)) {
                unset($this->headers[$pos]);
            }
            $this->headers['enabledFieldName'] = $this->extraMapping['enabledFieldName'];
        }
        if (!empty($this->extraMapping['categoryFieldName'])) {
            if ($pos = array_search($this->extraMapping['categoryFieldName'], $this->headers)) {
                unset($this->headers[$pos]);
            }
            $this->headers['categoryFieldName'] = $this->extraMapping['categoryFieldName'];
        }
        if (!empty($this->extraMapping['familyFieldName'])) {
            if ($pos = array_search($this->extraMapping['familyFieldName'], $this->headers)) {
                unset($this->headers[$pos]);
            }
            $this->headers['familyFieldName'] = $this->extraMapping['familyFieldName'];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function convert(array $item, array $options = []): array
    {
        $this->multipleImageField = [];
        $parent = null;
        if ($this->storeTmpName === 'wk_akeneo_shopify_csv_export' && in_array('Handle', $this->headers)) {
            $parent = 'Handle';
        }
        
        $data = $this->formatData($item, $parent);
        $myArray = [];
        $default_array =[];
        foreach ($data as $data_key => $data_value) {
            $getData = [];
            foreach ($this->headers as $head) {
                if (!empty($data_value[$head])) {
                    if (is_array($data_value[$head])) {
                        if ($this->storeTmpName === 'wk_akeneo_shopify_csv_export') {
                            $this->multipleImageField[] = $head;
                            $getData[] = $data_value[$head][0];
                            unset($data[$data_key][$head][0]);
                        }
                    } elseif (in_array($head, $this->variantAxesField) && isset($item['parent']) && $this->storeTmpName === 'wk_akeneo_magento2_csv_export') {
                        /** Store Akeneo variant Sku and Variant axes value to export variant on Magento2 */
                        $this->magentoConfigurationVariations[$item['parent']] [] = [
                            'sku' => $item['values']['sku'][0]['data'],
                            $head => $data_value[$head]
                        ];
                        
                        $getData[] = "";
                    } else {
                        $getData[] = $data_value[$head];
                    }
                } elseif (in_array($head, $this->productCustomHeaders)) {
                    /** Format product type for BigCommerce and Magento*/
                    $getData[] = $this->productCustomType->formatProductType($head, $this->productCustomType, $item);
                } else {
                    $getData[] = "";
                }
            }
            if ($getData) {
                $myArray [] = $getData;
            }
        }
       
        foreach ($myArray as $pushArray) {
            array_push($default_array, $pushArray);
        }

        /**  Format Stored Akeneo variant Sku, Variant axes value for Magento2 */
        if (isset($item['code']) && $this->storeTmpName === 'wk_akeneo_magento2_csv_export') {
            if (isset($this->magentoConfigurationVariations[$item['code']])) {
                $variantValues = $this->magentoConfigurationVariations[$item['code']];
                $default_array = $this->magento2ClassObject->formatConfigurableVariations($variantValues, $this->headers, $default_array, $item['code']);
                unset($this->magentoConfigurationVariations[$item['code']]);
            }
        }
        $default_array['data'] = $data;

        return $default_array;
    }

    /**
     * @param \StepExecution $stepExecution
     */
    public function setStepExecution(\StepExecution $stepExecution)
    {
        $this->stepExecution = $stepExecution;
        $this->initializeRequirements();
    }
}
