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

namespace Autogedal\AjaxcartCustom\Plugin\Block\Product;

use Tigren\Ajaxcart\Block\Product\Image;
use Magento\Framework\Registry;
use Magento\Framework\App\ObjectManager;

/**
 * Plugin to fix product image URL generation in AJAX cart
 */
class ImagePlugin
{
    /**
     * @var Registry
     */
    protected $_coreRegistry;

    /**
     * @param Registry $registry
     */
    public function __construct(
        Registry $registry
    ) {
        $this->_coreRegistry = $registry;
    }

    /**
     * Fix image URL generation to not rely on hardcoded attribute IDs
     *
     * @param Image $subject
     * @param callable $proceed
     * @return string
     */
    public function aroundGetImageUrl(Image $subject, callable $proceed)
    {
        $objectManager = ObjectManager::getInstance();
        $product = $this->_coreRegistry->registry('current_product');
        
        if (!$product) {
            $product = $this->_coreRegistry->registry('product');
        }
        
        if ($product) {
            try {
                $imageUrl = $objectManager->get('Tigren\Ajaxcart\Helper\Data')->getProductImageUrl(
                    $product,
                    'category'
                );
                return $imageUrl;
            } catch (\Exception $e) {
                // Fall back to original method if there's an error
            }
        }
        
        return $proceed();
    }
}