<?php

namespace KupShop\FeedsBundle;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\FeedsBundle\Query\FeedProductModifiers;
use KupShop\I18nBundle\Translations\ProductsTranslation;
use KupShop\I18nBundle\Translations\VariationsTranslation;
use Query\QueryBuilder;
use Query\Translation;

class FeedProductList extends \ProductList
{
    protected function createQueryBuilder($useTotalCount)
    {
        $qb = parent::createQueryBuilder($useTotalCount);

        $qb->andWhere(Translation::coalesceTranslatedFields(
            ProductsTranslation::class,
            ['title', 'long_descr', 'parameters']
        ));

        if (findModule(\Modules::PRODUCTS_VARIATIONS)) {
            $qb->andWhere(Translation::coalesceTranslatedFields(
                VariationsTranslation::class,
                ['title' => 'variation_title', 'figure' => 'variationVisible']
            ));
        }

        if (!findModule(\Modules::XML_FEEDS, \Modules::SUB_DISABLE_ZERO_PRICE_FILTER)) {
            $qb->andWhere('COALESCE(pv.price, p.price) > 0');
        }

        return $qb;
    }

    /**
     * @param int $totalCount if provided, $totalCount will be set to total count of found rows limit applied
     *
     * @return FeedProductCollection
     */
    public function getProducts(&$totalCount = null)
    {
        $useTotalCount = count(func_get_args());

        $products = [];
        $dataAll = [];
        $qb = $this->createQueryBuilder($useTotalCount);
        $result = $qb->execute();

        if ($useTotalCount) {
            $totalCount = (int) sqlQuery('SELECT FOUND_ROWS() as total_count')->fetchColumn();
        }

        foreach ($result as $row) {
            if ($this->variationsAsResult && $row['id_variation'] !== null) {
                $product = new FeedVariation();
            } else {
                $product = new FeedProduct();
            }
            $product->createFromArray($row);

            $id = $product->id;
            if ($product instanceof \Variation) {
                $id .= '/'.$product->variationId;
            }

            $products[$id] = $product;
            $dataAll[$id] = $row;
        }

        $productCollection = (new FeedProductCollection($products))
            ->setEntityType($this->variationsAsResult ? \FilterParams::ENTITY_VARIATION : \FilterParams::ENTITY_PRODUCT);

        foreach ($this->resultModifiers as $callback) {
            $callback($productCollection, $dataAll);
        }

        return $productCollection;
    }

    public function getSelectFields($qb = null)
    {
        $fields = parent::getSelectFields($qb);
        $firstKey = array_key_first($fields);
        $fields[$firstKey] = 'SQL_NO_CACHE '.$fields[$firstKey];
        $fields['product_code'] = 'p.code';
        if (findModule(\Modules::PRODUCTS_VARIATIONS, \Modules::SUB_CODE)) {
            $fields['code'] = 'COALESCE(pv.code, p.code)';
        }
        $fields['ean'] = 'COALESCE(pv.ean, p.ean)';

        if (findModule(\Modules::MISSING_PRODUCTS)) {
            $fields['in_store_min'] = $this->variationsAsResult ? 'COALESCE(pv.in_store_min, p.in_store_min)' : 'p.in_store_min';
        }

        if (findModule(\Modules::PRODUCTS, \Modules::SUB_NOTE)) {
            $fields['note_'] = 'COALESCE(GROUP_CONCAT(DISTINCT NULLIF(pv.note, "")), p.note)';
        }

        return $fields;
    }

    public function fetchGifts(int $feedID)
    {
        $this->resultModifiers[] = FeedProductModifiers::addGifts($feedID);

        return $this;
    }

    public function fetchVariationLabels()
    {
        $this->resultModifiers[] = function (ProductCollection $products) {
            $this->multiFetch->fetchVariationLabels($products);
        };

        return $this;
    }

    public function withPhotos()
    {
        $this->andSpec(function (QueryBuilder $qb) {
            $qb->andWhere('ppr.id_photo IS NOT NULL');
        });
    }
}
