<?php
/**
 * Copyright © Banyo. All rights reserved.
 */

namespace Banyo\CheckoutFix\Plugin\Checkout\Controller\Cart;

use Magento\Checkout\Controller\Cart\UpdateItemOptions;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\UrlInterface;

class UpdateItemOptionsPlugin
{
    /**
     * @var RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var UrlInterface
     */
    protected $url;

    /**
     * @param RedirectFactory $resultRedirectFactory
     * @param RequestInterface $request
     * @param UrlInterface $url
     */
    public function __construct(
        RedirectFactory $resultRedirectFactory,
        RequestInterface $request,
        UrlInterface $url
    ) {
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->request = $request;
        $this->url = $url;
    }

    /**
     * Around execute plugin
     *
     * @param UpdateItemOptions $subject
     * @param \Closure $proceed
     * @return Redirect
     */
    public function aroundExecute(UpdateItemOptions $subject, \Closure $proceed)
    {
        // Get the referer URL before proceeding with the original execution
        $refererUrl = $this->request->getServer('HTTP_REFERER');

        // Get the item ID from the request
        $itemId = (int)$this->request->getParam('id');

        try {
            // Execute the original method
            $result = $proceed();

            // If the result is a redirect and we have a referer URL, modify it to redirect back to the referer
            // with parameters to open the cart drawer and preserve the item ID
            if ($result instanceof Redirect && $refererUrl) {
                // Add parameters to trigger the cart drawer to open and preserve the item ID
                $separator = (strpos($refererUrl, '?') !== false) ? '&' : '?';
                $redirectUrl = $refererUrl . $separator . 'open_cart=1';

                // Only add the id parameter if it's not already in the URL
                if (strpos($redirectUrl, 'id=' . $itemId) === false && $itemId > 0) {
                    $redirectUrl .= '&id=' . $itemId;
                }

                return $this->resultRedirectFactory->create()->setUrl($redirectUrl);
            }

            return $result;
        } catch (\Exception $e) {
            // If an exception occurs, redirect to the cart page
            $this->request->getSession()->addError($e->getMessage());
            return $this->resultRedirectFactory->create()->setPath('checkout/cart');
        }
    }
}
