<?php

namespace Banyo\CustomCategory\ViewModel;

use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\Layer\Resolver as LayerResolver;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;

class BestSeller implements ArgumentInterface
{
    private LayerResolver $layerResolver;
    private CategoryFactory $categoryFactory;

    public function __construct(
        LayerResolver $layerResolver,
        CategoryFactory $categoryFactory
    ) {
        $this->layerResolver = $layerResolver;
        $this->categoryFactory = $categoryFactory;
    }

    public function getBestSellerData(): array
    {
        $layer = $this->layerResolver->get();
        $currentCategory = $layer->getCurrentCategory();

        if (!$currentCategory || !$currentCategory->getId()) {
            return ['products' => [], 'url' => '', 'name' => ''];
        }

        $childCategories = $currentCategory->getChildrenCategories();

        foreach ($childCategories as $childCategory) {
            if (strcasecmp(trim($childCategory->getName()), 'Best Sellers') === 0) {
                $loadedCategory = $this->categoryFactory->create()->load($childCategory->getId());

                $productCollection = $loadedCategory->getProductCollection()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('status', Status::STATUS_ENABLED)
                    ->setPageSize(4);

                return [
                    'products' => $productCollection,
                    'url' => $loadedCategory->getUrl(),
                    'name' => $loadedCategory->getName(),
                ];
            }
        }

        return ['products' => [], 'url' => '', 'name' => ''];
    }
}
