<?php

namespace FiloBlu\Flow\Model\Actions\From;
use Exception;
use FiloBlu\Flow\Helper\Data;
use Magento\Catalog\Model\Product;

/**
 * Class Setdefaultforlocale
 * @package FiloBlu\Flow\Model\Actions\From
 */
class Setdefaultforlocale
{

    /**
     * @var string
     */
    CONST ENTITY_TYPE_CODE = 'catalog_product';

    /**
     * @var Data
     */
    protected $helperData;

    /**
     * @var Product
     */
    protected $productFactory;

    /**
     * Setdefaultforlocale constructor.
     * @param Data $helperData
     * @param Product $productFactory
     */
    public function __construct(
        Data $helperData,
        Product $productFactory
    )
    {
        $this->helperData = $helperData;
        $this->productFactory = $productFactory;
    }

    /**
     * @param $attribute
     * @param $value
     * @param $storeId
     * @throws Exception
     */
    public function process($attribute, $value, $storeId)
    {

        if (empty($value)) {
            throw new Exception("Invalid value supplied '{$value}'");
        }

        // separatore |||
        $explode = explode('|||', $value);

        $_attribute_value = $explode[0];
        $_stores = explode(';', $explode[1]);
        $_sku = $explode[2];

        $_store_ids = $this->helperData->getAllStoreIds();

        $product_id = $this->productFactory->create()->getIdBySku($_sku);
        $product = $this->productFactory->create()->setStoreId(0)->load($product_id);

        $product->setData($attribute->getAttributeCode(), $_attribute_value);
        $product->save();

        if (is_array($_stores) && count($_stores) >= 1) {

            foreach ($_stores as $store) {

                $_store_id = $_store_ids[$store];
                // set "use default" for attribute in store view
                // $this->_logger->info('store ID: '.$_store_id . ' - '.$attribute->getAttributeCode() . ' ID: ' .$product->getId());

                $product = $this->productFactory->create()->setStoreId($_store_id)->load($product_id);
                $product->setData($attribute->getAttributeCode(), '');
                $product->setData($attribute->getAttributeCode(), false);
                $product->save();
            }

        }
    }

}
