<?php
declare(strict_types=1);

namespace Banyo\SeoFix\Plugin;

use Magento\Catalog\Block\Product\View;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\UrlInterface;

class OpenGraphImagePlugin
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    public function __construct(
        StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    /**
     * Replace the OpenGraph image URL with the store logo for homepage
     *
     * @param View $subject
     * @param mixed $result
     * @param mixed $product
     * @param string $imageId
     * @return mixed
     */
    public function afterGetImage(View $subject, $result, $product = null, $imageId = null)
    {
        $fullActionCode = $subject->getRequest()->getFullActionName();

        if ($fullActionCode === 'cms_index_index') {
            // Create a custom object that has getImageUrl method
            return new class($this->storeManager) {
                private $storeManager;

                public function __construct($storeManager) {
                    $this->storeManager = $storeManager;
                }

                public function getImageUrl() {
                    return $this->storeManager
                        ->getStore()
                        ->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
                    . 'logo/stores/1/BanyoStoreLogo.png';
                }
            };
        }

        return $result;
    }
}
