<?php

namespace KupShop\CatalogBundle\Util;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\CatalogBundle\Query\RelatedProducts;
use Query\QueryBuilder;

class RelatedProductsUtil
{
    public function getRelatedProductList(array $productIds, ?array $related_type = null): \ProductList
    {
        $productList = new \ProductList();
        $productList->applyDefaultFilterParams();
        $productList->setVariationsAsResult(true); // TODO: HOTFIX, predelat

        $productList->andSpec(RelatedProducts::relatedProductsSpec($productIds, $related_type));
        $productList->andSpec(function (QueryBuilder $qb) {
            $qb->addSelect("CONCAT(pr.id_top_product, '_', pr.id_rel_product) AS id");
            $qb->addSelect('NULL as id_variation, p.code, p.delivery_time, p.ean, p.figure, p.width, p.height, p.depth, p.date_added');
            $in_store_field = \Query\Product::getInStoreField(false, $qb);
            $qb->addSelect("{$in_store_field} AS in_store");
            if (findModule(\Modules::PRODUCTS_RELATED, \Modules::SUB_TYPES)) {
                $qb->addSelect('GROUP_CONCAT(pr.type) as types');
            }
            $qb->groupBy('pr.id_top_product, pr.id_rel_product');
            $qb->orderBySql('pr.id_top_product ASC, pr.position ASC');
        });

        $productList->addResultModifiers(function (ProductCollection $products, $dataAll) {
            foreach ($dataAll as $productId => $data) {
                $products[$productId]->id_top_product = $data['id_top_product'];
                $products[$productId]->id_rel_product = $data['id_rel_product'];
                $products[$productId]->id = $products[$productId]->id_rel_product;
                if (findModule(\Modules::PRODUCTS_RELATED, \Modules::SUB_TYPES)) {
                    $products[$productId]->related_types = array_map('intval', explode(',', $data['types']));
                }
            }
        });

        return $productList;
    }
}
