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

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

use Magento\Checkout\Controller\Cart\Configure;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;

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

    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param RedirectFactory $resultRedirectFactory
     * @param ManagerInterface $messageManager
     * @param ProductRepositoryInterface $productRepository
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        RedirectFactory $resultRedirectFactory,
        ManagerInterface $messageManager,
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManager
    ) {
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->messageManager = $messageManager;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
    }

    /**
     * Around execute plugin
     *
     * @param Configure $subject
     * @param callable $proceed
     * @return mixed
     */
    public function aroundExecute(Configure $subject, callable $proceed)
    {
        $productId = (int)$subject->getRequest()->getParam('product_id');

        try {
            // Try to load the product
            $storeId = $this->storeManager->getStore()->getId();
            $product = $this->productRepository->getById($productId, false, $storeId);

            // Check if the product is visible in the current store
            if (!$product->isVisibleInCatalog() || !$product->isVisibleInSiteVisibility()) {
                $this->messageManager->addErrorMessage(
                    __('The product is not available in the current store. Please contact customer support for assistance.')
                );
                return $this->resultRedirectFactory->create()->setPath('checkout/cart');
            }

            // Check if the product is available in the current website
            if (!in_array($this->storeManager->getStore()->getWebsiteId(), $product->getWebsiteIds())) {
                $this->messageManager->addErrorMessage(
                    __('The product is not available in the current website. Please contact customer support for assistance.')
                );
                return $this->resultRedirectFactory->create()->setPath('checkout/cart');
            }

            // If we get here, the product exists and is visible, so proceed with the original execution
            return $proceed();

        } catch (NoSuchEntityException $e) {
            // Product doesn't exist
            $this->messageManager->addErrorMessage(
                __('The product that was requested doesn\'t exist. It may have been removed from the catalog. Please contact customer support for assistance.')
            );
            return $this->resultRedirectFactory->create()->setPath('checkout/cart');
        } catch (\Exception $e) {
            // Any other exception
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your request. Please try again later or contact customer support.')
            );
            return $this->resultRedirectFactory->create()->setPath('checkout/cart');
        }
    }
}
