<?php
declare(strict_types=1);

namespace Banyo\CustomHomePage\Plugin\Catalog\Model;

use Magento\Catalog\Model\Category;
use Magento\Store\Model\StoreManagerInterface;

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

    /**
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    /**
     * Add getMobileImageUrl method to Category model
     *
     * @param Category $subject
     * @param callable $proceed
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function aroundCall(
        Category $subject,
        callable $proceed,
        string $method,
        array $args = []
    ) {
        if ($method === 'getMobileImageUrl') {
            return $this->getMobileImageUrl($subject);
        }

        return $proceed($method, $args);
    }

    /**
     * Get mobile image URL
     *
     * @param Category $category
     * @return string|null
     */
    private function getMobileImageUrl(Category $category): ?string
    {
        $mobileImage = $category->getMobileImage();
        if (!$mobileImage) {
            return null;
        }

        $baseUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        return $baseUrl . 'catalog/category/' . $mobileImage;
    }
}
