<?php
/**
 * Plumrocket Inc.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the End-user License Agreement
 * that is available through the world-wide-web at this URL:
 * http://wiki.plumrocket.net/wiki/EULA
 * If you are unable to obtain it through the world-wide-web, please
 * send an email to support@plumrocket.com so we can send you a copy immediately.
 *
 * @package     Plumrocket Product Filter v3.x.x
 * @copyright   Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
 * @license     http://wiki.plumrocket.net/wiki/EULA  End-user License Agreement
 */

namespace Plumrocket\ProductFilter\Observer;

use Magento\Framework\Event\ObserverInterface;
use Plumrocket\ProductFilter\Model\Config\Source\Placement as FilterPlacement;

class MoveBlock implements ObserverInterface
{
    /**
     * Data helper
     * @var \Plumrocket\ProductFilter\Helper\Data
     */
    protected $_dataHelper;

    /**
     * @var \Plumrocket\ProductFilter\Model\Magento\VersionProvider
     */
    private $versionProvider;

    /**
     * Construct
     *
     * @param \Plumrocket\ProductFilter\Helper\Data                   $dataHelper
     * @param \Plumrocket\ProductFilter\Model\Magento\VersionProvider $versionProvider
     */
    public function __construct(
        \Plumrocket\ProductFilter\Helper\Data $dataHelper,
        \Plumrocket\ProductFilter\Model\Magento\VersionProvider $versionProvider
    ) {
        $this->_dataHelper = $dataHelper;
        $this->versionProvider = $versionProvider;
    }

    /**
     * Changing attribute values
     * @param  \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->_dataHelper->moduleEnabled()) {
            /**
             * @var \Magento\Framework\View\Layout $layout
             */
            $layout = $observer->getLayout();
            if (array_intersect($layout->getUpdate()->getHandles(), $this->_dataHelper->getAllowedHandles())) {
                $layout->getUpdate()->addHandle('product_filter_init');
                if ($this->_dataHelper->getPlacement() == FilterPlacement::PLACEMENT_TOOLBAR) {
                    if ($this->versionProvider->isMagentoVersionBelow('2.3.0')) {
                        $layout->getUpdate()->addHandle('product_filter_toolbar');
                    } else {
                        $layout->getUpdate()->addHandle('product_filter_toolbar_for_newer');
                    }
                }
            }
        }
    }
}
