<?php

declare(strict_types=1);

namespace KupShop\CatalogBundle\View;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\CatalogBundle\ProductList\ProductList;
use KupShop\CatalogBundle\Section\SectionTree;
use KupShop\KupShopBundle\Views\View;
use Query\Operator;
use Query\Product;

class SearchPreloadView extends View
{
    protected $template = 'search/search.preload.tpl';

    protected ProductList $productList;
    protected SectionTree $sectionTree;

    public function __construct(ProductList $productList, SectionTree $sectionTree)
    {
        $this->productList = $productList;
        $this->sectionTree = $sectionTree;
    }

    public function getBodyVariables()
    {
        $vars = parent::getBodyVariables();

        return array_merge($vars, $this->getPreloadData());
    }

    protected function getPreloadData()
    {
        $vars = [];

        $dbcfg = \Settings::getDefault();

        $config = $dbcfg->fulltext['preload'] ?? [];

        foreach (['products', 'sections', 'producers'] as $type) {
            $method = 'preload'.ucfirst($type);
            if (method_exists($this, $method)) {
                $vars[$type] = $this->{$method}($config[$type] ?? []);
            }
        }

        return $vars;
    }

    protected function preparePreloadProductList(array $ids): ProductList
    {
        $this->productList->applyDefaultFilterParams();
        $this->productList->andSpec(Product::productsIds($ids));
        $this->productList->fetchImages(2);

        return $this->productList;
    }

    protected function preloadProducts(array $ids): ProductCollection
    {
        return $this->preparePreloadProductList($ids)->getProducts();
    }

    protected function preloadSections(array $ids): array
    {
        $result = [];
        foreach ($ids as $id) {
            $result[$id] = $this->sectionTree->getSectionById($id);
        }

        return $result;
    }

    public function preloadProducers(array $ids): array
    {
        if (!findModule(\Modules::PRODUCERS)) {
            return [];
        }

        $qb = sqlQueryBuilder()
            ->select('pr.id, pr.name')
            ->from('producers', 'pr')
            ->where(Operator::inIntArray($ids, 'pr.id'));

        $result = [];
        foreach ($qb->execute() as $item) {
            $result[$item['id']] = [
                'id' => (int) $item['id'],
                'name' => $item['name'],
            ];
        }

        return $result;
    }
}
