<?php

namespace Banyo\CustomHomePage\ViewModel;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;

class PremiereSubCategory implements ArgumentInterface
{
    const CONFIG_PATH_PREFIX = 'premiere_theme/subcat_section/';

    protected $scopeConfig;
    protected $storeManager;

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

    public function getSubCategoryItems(): array
    {
        $items = [];
        $mediaBase = $this->getMediaUrl();

        for ($i = 1; $i <= 5; $i++) {
            $desktopImage = $this->getConfigValue("subcat_section_desktop_img_{$i}");
            $mobileImage = $this->getConfigValue("subcat_section_mobile_img_{$i}");
            $urlKey = $this->getConfigValue("subcat_section_link_{$i}");

            if ($desktopImage && $mobileImage) {
                $items[] = [
                    'desktopImage' => $mediaBase . 'wysiwyg/' . ltrim((string)$desktopImage, '/'),
                    'mobileImage'  => $mediaBase . 'wysiwyg/' . ltrim((string)$mobileImage, '/'),
                    'url'          => '/' . ltrim((string)$urlKey, '/')
                ];
            }
        }

        return $items;
    }

    public function getConfigValue(string $key): ?string
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_PATH_PREFIX . $key,
            ScopeInterface::SCOPE_STORE
        );
    }

    protected function getMediaUrl(): string
    {
        return rtrim(
                $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA),
                '/'
            ) . '/';
    }

    public function getImageUrl(string $configPath): string
    {
        $imagePath = $this->getConfigValue($configPath);
        return $imagePath ? $this->getMediaUrl() . ltrim($imagePath, '/') : '';
    }
}
