<?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 SaveUp implements ArgumentInterface
{
    const CONFIG_PATH_PREFIX = 'nexus_theme/save_up/';

    protected $scopeConfig;
    protected $storeManager;

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

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

        for ($i = 1; $i <= 5; $i++) {
            $image = $this->getConfigValue("save_up_img_{$i}");
            $urlKey = $this->getConfigValue("save_up_redirect_link_{$i}");

            if ($image) {
                $items[] = [
                    'image' => $mediaBase . 'wysiwyg/' . ltrim($image, '/'),
                    'url' => '/' . ltrim($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, '/') : '';
    }
}
