<?php

namespace External\LeaflyBundle\Query;

use KupShop\I18nBundle\Translations\ProductsTranslation;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;
use Query\QueryBuilder;
use Query\Translation;
use Query\Variation;

class Filter
{
    public static function isVisible($visible)
    {
        $userContext = ServiceContainer::getService(UserContext::class);
        $expressions = [function (QueryBuilder $qb) use ($userContext) {
            $qb->setParameter('visible', 'Y')
                ->setParameter('vo_campaign', 'VO')
                ->setParameter('ed_campaign', 'ED')
                ->setParameter('b2c_campaign', 'B2C');
            $qb->andWhere(
                Translation::joinTranslatedFields(
                    ProductsTranslation::class,
                    function (QueryBuilder $qb, $columnName, $translatedField) use ($userContext) {
                        $activeUser = $userContext->getActive();
                        $qb->leftJoin('p', 'photos_products_relation', 'pprel', 'p.id=pprel.id_product AND pprel.show_in_lead=\'Y\'');
                        $qb->andWhere('pprel.id_photo IS NOT NULL');

                        if (!$activeUser || !($activeUser->hasGroupId(3) || $activeUser->hasGroupId(1330))) {
                            $where = ' AND FIND_IN_SET(:b2c_campaign, p.campaign) > 0';
                        } elseif ($activeUser->hasGroupId(3)) {
                            $where = ' AND FIND_IN_SET(:vo_campaign, p.campaign) > 0';
                        } else {
                            $where = ' AND FIND_IN_SET(:ed_campaign, p.campaign) > 0';
                        }

                        if ($translatedField != null) {
                            $qb->andWhere("COALESCE({$translatedField}, p.{$columnName}) = :visible".$where);
                        } else {
                            $qb->andWhere('p.figure = :visible'.$where);
                        }

                        return false;
                    },
                    ['figure']
                )
            );
        }];

        if ($visible === \FilterParams::ENTITY_VARIATION) {
            $expressions[] = Variation::isVisible();
        }

        return Operator::andX($expressions);
    }
}
