<?php

namespace FiloBlu\Flow\Model;

use Exception;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\ValueFactory;
use Magento\Framework\App\Config\ValueInterface;
use Magento\Framework\DataObject;
use Magento\Framework\DB\Transaction;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Class Config
 * @package FiloBlu\Flow\Model
 */
class Config extends DataObject
{

    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var ScopeConfigInterface
     */
    protected $_scopeConfig;
    /**
     * @var ValueInterface
     */
    protected $_backendModel;
    /**
     * @var Transaction
     */
    protected $_transaction;
    /**
     * @var ValueFactory
     */
    protected $_configValueFactory;
    /**
     * @var int $_storeId
     */
    protected $_storeId;
    /**
     * @var string $_storeCode
     */
    protected $_storeCode;

    /**
     * Config constructor.
     * @param StoreManagerInterface $storeManager
     * @param ScopeConfigInterface $scopeConfig
     * @param ValueInterface $backendModel
     * @param Transaction $transaction
     * @param ValueFactory $configValueFactory
     * @param array $data
     * @throws NoSuchEntityException
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig,
        ValueInterface $backendModel,
        Transaction $transaction,
        ValueFactory $configValueFactory,
        array $data = []
    ) {
        parent::__construct($data);
        $this->_storeManager = $storeManager;
        $this->_scopeConfig = $scopeConfig;
        $this->_backendModel = $backendModel;
        $this->_transaction = $transaction;
        $this->_configValueFactory = $configValueFactory;
        $this->_storeId = $this->_storeManager->getStore()->getId();
        $this->_storeCode = $this->_storeManager->getStore()->getCode();
    }

    /**
     * @param $path
     * @return mixed
     */
    public function getCurrentStoreConfigValue($path)
    {
        return $this->_scopeConfig->getValue($path, 'store', $this->_storeCode);
    }

    /**
     * @param $path
     * @param $value
     * @throws Exception
     */
    public function setCurrentStoreConfigValue($path, $value)
    {
        $data = [
            'path' => $path,
            'scope' => 'stores',
            'scope_id' => $this->_storeId,
            'scope_code' => $this->_storeCode,
            'value' => $value,
        ];

        $this->_backendModel->addData($data);
        $this->_transaction->addObject($this->_backendModel);
        $this->_transaction->save();
    }
}
