<?php

namespace KupShop\FeedsBundle\Query;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\I18nBundle\Translations\VariationsLabelsTranslation;
use Query\Operator;
use Query\Translation;

class FeedProductModifiers
{
    public static function addVariationLabelAndValue(): callable
    {
        return function (ProductCollection $products) {
            $product_variations = array_filter($products->getValues(), function ($p) { return !empty($p['variationId']); });
            $variationIds = array_column($product_variations, 'variationId');
            $product_variations = array_combine($variationIds, $product_variations);

            $qb = sqlQueryBuilder()->select('pvc.*, pvcl.label, pvcv.value')
                ->from('products_variations_combination', 'pvc')
                ->leftJoin('pvc', 'products_variations_choices_labels', 'pvcl', 'pvc.id_label = pvcl.id')
                ->leftJoin('pvc', 'products_variations_choices_values', 'pvcv', 'pvc.id_value = pvcv.id')
                ->where(Operator::inIntArray($variationIds, 'pvc.id_variation'))
                ->andWhere(
                    Translation::coalesceTranslatedFields(VariationsLabelsTranslation::class)
                );

            $SQL = $qb->execute();

            foreach ($SQL as $variation) {
                $id_variation = $variation['id_variation'];
                $product_variations[$id_variation]->variations[$variation['id_label']] = $variation;
            }
        };
    }

    public static function addProductPhotoToVariation(): callable
    {
        return function (ProductCollection $products) {
            $variations = array_filter($products->getValues(), function ($p) { return !empty($p['variationId']) && empty($p['photoId']); });
            $productIds = array_unique(array_column($variations, 'id'));

            $photos = sqlQueryBuilder()->select('p.id_product, p.id_photo')
                ->from('photos_products_relation', 'p')
                ->where('p.id_variation IS NULL AND p.show_in_lead=\'Y\'')
                ->andWhere(Operator::inIntArray($productIds, 'p.id_product'))
                ->execute()->fetchAll();
            $photos = array_combine(array_column($photos, 'id_product'), $photos);

            foreach ($variations as $variation) {
                $id_product = $variation->id;
                if (isset($photos[$id_product])) {
                    $variation->photoId = $photos[$id_product]['id_photo'];
                }
            }
        };
    }

    public static function addGifts(int $feedID): callable
    {
        return function (ProductCollection $products) use ($feedID) {
            if (!findModule(\Modules::FEED_GIFTS) || !findModule(\Modules::PRODUCT_GIFTS)) {
                return;
            }

            $qb = sqlQueryBuilder()
                ->select('pg.id_product AS id_product, p.id AS id, pg.id_variation_gift AS selected_variation, '
                    .'pg.pieces AS set_pieces, COALESCE(psfp.gift_text, p.title) AS text, p.title AS title')
                ->from('products', 'p')
                ->join('p', 'products_gifts', 'pg', 'p.id = pg.id_product_gift')
                ->joinVariationsOnProducts()
                ->leftJoin('p', 'feed_products', 'psfp', 'psfp.id_product = p.id AND psfp.id_feed = :psfp_id_feed')
                ->setParameter('psfp_id_feed', $feedID)
                ->andWhere(Operator::inIntArray($products->getProductIds(), 'pg.id_product'))
                ->andWhere('pv.id = pg.id_variation_gift OR pg.id_variation_gift IS NULL')
                ->groupBy('pg.id_product, p.id')
                ->orderBy('pg.id_product, p.id, pg.id_variation_gift');
            $data = [];
            foreach ($qb->execute() as $setProduct) {
                $data[$setProduct['id_product']] = $data[$setProduct['id_product']] ?? [];
                $data[$setProduct['id_product']][] = $setProduct;
            }
            $products->forAll(function ($key, &$product) use ($data) {
                if (isset($data[$product->id])) {
                    $product->gifts = $data[$product->id];
                }

                return true;
            });
        };
    }
}
