<?php


namespace Magetop\Advancepreview\Observer\Frontend;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class OpdOptions implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\Request\Http
     */
    protected $http;
    /**
     * @var \Magento\Framework\Serialize\Serializer\Json
     */
    protected $json;
    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;

    /**
     * OpdOptions constructor.
     * @param \Magento\Framework\App\Request\Http $http
     * @param \Magento\Framework\Serialize\Serializer\Json $json
     * @param \Magento\Checkout\Model\Cart $cart
     */
    function __construct(
        \Magento\Framework\App\Request\Http $http,
        \Magento\Framework\Serialize\Serializer\Json $json,
        \Magento\Checkout\Model\Cart $cart
    )
    {
        $this->http = $http;
        $this->json = $json;
        $this->cart = $cart;
    }

    public function execute(Observer $observer)
    {

        $actionName = "";
        try {
            $action = $this->http;
            if($action) {
                $actionName = $this->http->getFullActionName();
            }
        } catch(\Exception $e) {
            $actionName = "";
        }
        if ($actionName == 'checkout_cart_add' || $actionName == 'checkout_cart_updateItemOptions')
        {
            $addOptions = [
                [
                    'label'=>'test',
                    'value'=>time(),
                ]
            ];
            /** @var \Magento\Catalog\Model\Product $product*/

            // assuming you are posting your custom form values in an array called extra_options...
            $params = $this->http->getParams();
            $product = $observer->getData('product');
            $itemId = (int)isset($params['item']) ? $params['item'] : 0;
            if($itemId > 0) {
                $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/remoev.log');
                $logger = new \Zend\Log\Logger();
                $logger->addWriter($writer);
                $logger->info('remove ok keke '.$itemId);
               $this->cart->removeItem($itemId);
            }
            $product = $observer->getData('product');
            if(count($addOptions)) {
                $bookOptions = $this->json->serialize($addOptions);
                $product->addCustomOption('additional_options', $bookOptions);
            }

        }

    }
}
