<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Aitoc\PreOrders\Model\AttributesManagement;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Model\Product as ProductModel;

/**
 * Class SaveProductPreOrderSettings
 */
class SaveProductPreOrderSettings implements ObserverInterface
{
    /**
     * @var AttributesManagement
     */
    private $attributesManagement;

    /**
     * @var HttpRequest
     */
    private $request;

    /**
     * @param AttributesManagement $attributesManagement
     * @param HttpRequest $request
     */
    public function __construct(
        AttributesManagement $attributesManagement,
        HttpRequest $request
    ) {
        $this->attributesManagement = $attributesManagement;
        $this->request = $request;
    }

    /**
     * Save PreOrder setting for product
     *
     * @param Observer $observer
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        /** @var ProductModel $product */
        $product = $observer->getEvent()->getProduct();
        if (!$product) {
            return;
        }

        $useDefaultData = $this->request->getPost('use_default') ?: [];
        $productId = $product->getId();
        $storeId = $product->getStoreId();

        foreach ($this->attributesManagement->getAttributesList() as $attributeCode) {
            if (array_key_exists($attributeCode, $useDefaultData) && $useDefaultData[$attributeCode] === '1') {
                $this->attributesManagement->removeAttributeValue($productId, $attributeCode, $storeId);
            } else {
                $value = $product->getData($attributeCode);
                if ($value === null) {
                    $value = '';
                }
                $this->attributesManagement->saveAttributeValue($productId, $attributeCode, $value, $storeId);
            }
        }
    }
}
