<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Observer;

use Exception;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Serialize\SerializerInterface;

/**
 * @class CategorySaveBeforeObserver
 * @package FiloBlu\Refilo\Model\Observer
 */
class CategorySaveBeforeObserver implements ObserverInterface
{

    /**
     * @var RequestInterface
     */
    private $request;
    /**
     * @var SerializerInterface
     */
    private $serializer;

    /**
     * @param RequestInterface $request
     * @param SerializerInterface $serializer
     */
    public function __construct(
        RequestInterface $request,
        SerializerInterface $serializer
    ) {
        $this->request = $request;
        $this->serializer = $serializer;
    }

    /**
     * @param Observer $observer
     * @throws Exception
     * @event catalog_category_save_before
     */
    public function execute(Observer $observer)
    {
        $category = $observer->getEvent()->getDataObject();
        $post = $this->request->getPost();

        if ($post['emotional_products']) {
            $keyToRemove = ['ep_page', 'ep_position', 'ep_column_spacing', 'ep_row_spacing'];
            $filteredEmotionalProducts['emotional_products'] = array_map(function($item) use ($keyToRemove) {
                return array_intersect_key($item, array_flip($keyToRemove));
            }, $post['emotional_products']['emotional_products']);

            $emotionalProducts = $this->serializer->serialize($filteredEmotionalProducts);
            $category->setEmotionalProducts($emotionalProducts);
        }
    }
}
