<?php

namespace Banyo\CustomHomePage\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Catalog\Model\Layer\Resolver as LayerResolver;
use Magento\Catalog\Model\Category;
use Mageplaza\Blog\Helper\Data as BlogHelper;


class ThirdParty implements ArgumentInterface
{
    private const XML_PATH = 'banyo_theme/';
    private $layerResolver;

    private $blogHelper;
    public function __construct(
        private ScopeConfigInterface $scopeConfig,
        private StoreManagerInterface $storeManager,
        LayerResolver $layerResolver,
        BlogHelper $blogHelper
    ) {
        $this->layerResolver = $layerResolver;
        $this->blogHelper = $blogHelper;
    }

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

    public function getCurrentCategoryName(): ?string
    {
        return $this->layerResolver->get()->getCurrentCategory()?->getName();
    }

    public function getBlogPostsForCurrentCategory()
    {
        $category = $this->layerResolver->get()->getCurrentCategory();
        if (!$category) {
            return [];
        }

        $blogCategory = $this->blogHelper->getFactoryByType(\Mageplaza\Blog\Helper\Data::TYPE_CATEGORY)
            ->create()
            ->getCollection()
            ->addFieldToFilter('name', ['eq' => $category->getName()])
            ->getFirstItem();

        if (!$blogCategory) {
            return [];
        }

        $collection = $blogCategory->getSelectedPostsCollection();
        $this->blogHelper->addStoreFilter($collection);
        $collection->addFieldToFilter('enabled', 1);
        $collection->setPageSize(4);

        $posts = [];
        foreach ($collection->getItems() as $post) {
            $posts[] = [
                'post' => $post,
                'topic' => ($post->getTopicIds() ? $this->blogHelper->getFactoryByType(\Mageplaza\Blog\Helper\Data::TYPE_TOPIC)
                    ->create()
                    ->load($post->getTopicIds()[0])
                    ->getName() : null) // Adjust method name if needed
            ];
        }

        return $posts;
    }

}
