<?php

namespace Banyo\CustomCategory\Observer;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Layout;
use Magento\Catalog\Model\Category;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

class CategoryLayout implements ObserverInterface
{
    private const CATEGORY_LAYOUT = 'catalog_category_view_parent_category_layout';
    private const ACTION_NAME = 'catalog_category_view';

    /**
     * @var CategoryRepositoryInterface
     */
    private $categoryRepository;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(
        CategoryRepositoryInterface $categoryRepository,
        \Magento\Framework\Registry $registry,
        StoreManagerInterface $storeManager,
        LoggerInterface $logger
    ) {
        $this->categoryRepository = $categoryRepository;
        $this->_registry = $registry;
        $this->storeManager = $storeManager;
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        $actionName = $observer->getEvent()->getFullActionName();
        if ($actionName !== self::ACTION_NAME) {
            return;
        }

        // Get current store code
        $currentStoreCode = $this->storeManager->getStore()->getCode();

        // Only apply for Nexus + Banyo, skip PremierDIY
        $allowedStoreCodes = ['nexus', 'banyo'];

        if (!in_array($currentStoreCode, $allowedStoreCodes, true)) {
            return; // Exit early for premierdiy or any other store
        }

        $category = $this->_registry->registry('current_category');
        /** @var Layout $layout */
        $layout = $observer->getLayout();

        $categoryId = (int) $category->getId();

        // Skip layout for specific category
        if ($categoryId === 191) {
            return;
        }

        if ($categoryId) {
            $category = $this->categoryRepository->get($categoryId);
            if ($this->isSecondLevelCategory($category)) {
                $layout->getUpdate()->addHandle(self::CATEGORY_LAYOUT);
            }
        }
    }

    /**
     * Check if the category is a second-level category (direct child of the root category)
     *
     * @param Category $category
     * @return bool
     */
    protected function isSecondLevelCategory(Category $category)
    {
        $parentCategoryId = $category->getParentId();
        $rootCategoryId = $this->storeManager->getStore()->getRootCategoryId();

        return $parentCategoryId == $rootCategoryId;
    }
}
