<?php
/**
 * 2007-2023 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2023 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

namespace PrestaShop\Module\AgileMultisellerPro\Hooks;

use Doctrine\ORM\EntityManagerInterface;
use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoCartCarrier;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoCommission;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoLang;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoLocationCarrier;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipCustomer;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipHistory;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoMembershipType;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoOrder;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoOrderDetail;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoProduct;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoRating;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoShipping;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\Commissions\DataConfiguration as CommissionsDataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\DataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\Membership\DataConfiguration as MembershipDataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperMembership;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperRating;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\DataColumn;
use PrestaShop\PrestaShop\Core\Grid\Filter\Filter;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

if (!defined('_PS_VERSION_')) {
    exit;
}

class AgileHooks
{
    use TraitAgileHooks;

    private static $instances = [];

    /** @var EntityManagerInterface */
    private $entityManager;

    private $sellerinfo;

    private $context;

    private function __construct()
    {
        $this->entityManager = AgileHelper::buildContainer()->get('doctrine.orm.entity_manager');

        $this->context = \Context::getContext();

        if (empty($this->sellerinfo) && $this->context->customer && $this->context->customer->id) {
            $sellerInfoRepository = $this->entityManager->getRepository(Sellerinfo::class);

            $this->sellerinfo = $sellerInfoRepository->findOneBy(['idCustomer' => $this->context->customer->id]);
        }
    }

    public static function getInstance(): self
    {
        $cls = static::class;

        if (!isset(self::$instances[$cls])) {
            self::$instances[$cls] = new static();
        }

        return self::$instances[$cls];
    }

    private function isSeller(): bool
    {
        if (
            $this->sellerinfo
            && $this->sellerinfo->getIdSellerinfo()
        ) {
            return true;
        }

        return false;
    }

    private function isSellerActive(): bool
    {
        if (
            $this->sellerinfo
            && true === $this->sellerinfo->isActive()
        ) {
            return true;
        }

        return false;
    }

    public function displayHookByName($hookName, $params = [])
    {
        $methodName = '_hook' . ucfirst($hookName);

        if (true === method_exists($this, $methodName)) {
            return $this->$methodName($params);
        }

        return null;
    }

    protected function _hookDisplayContentWrapperBottom()
    {
        if (
            \Configuration::get('AGILE_MS_CUSTOMER_SELLER')
            && $this->context->controller
            && $this->context->controller->php_self == 'authentication'
        ) {
            $this->context->smarty->assign([
                'sellersignupurl' => $this->context->link->getModuleLink(
                    'agilemultisellerpro', 'sellersignup', [], true),
            ]);

            return $this->context->smarty->fetch(
                'module:agilemultisellerpro/views/templates/hook/customerloginform.tpl'
            );
        }
    }

    protected function _hookDisplayFooter()
    {
        $this->context->smarty->assign([
            'linkSellersList' => $this->context->link->getModuleLink('agilemultisellerpro', 'agilesellers'),
        ]);

        return $this->context->smarty->fetch(
            'module:agilemultisellerpro/views/templates/hook/multipleshop-agilesellers-link.tpl'
        );
    }

    protected function _hookDisplayBeforeCarrier($params)
    {
        $sellerinfoShippingRepository = $this->entityManager->getRepository(SellerinfoShipping::class);

        $cartproducts = $this->context->cart->getProducts(false);
        if (!isset($cartproducts) || empty($cartproducts)) {
            return null;
        }

        $id_zone = AgileHelper::getZoneID(
            $this->context->cart->id_address_delivery,
            $this->context->cart->id_customer
        );

        $shippingData = $sellerinfoShippingRepository->groupProductsBySellerAndCalculateShipping(
            $cartproducts,
            $id_zone,
            $this->context->cart->id
        );

        $sellerinfoRepository = $this->entityManager->getRepository(Sellerinfo::class);
        $sellerinfoLangRepository = $this->entityManager->getRepository(SellerinfoLang::class);
        $sellerinfoCartCarrierRepository = $this->entityManager->getRepository(SellerinfoCartCarrier::class);

        foreach ($shippingData as $idSellerinfo => $shipping) {
            foreach ($shipping['products'] as $product) {
                if (!isset($shippingData[$idSellerinfo]['count_products'])) {
                    $shippingData[$idSellerinfo]['count_products'] = 0;
                }

                $shippingData[$idSellerinfo]['count_products'] += $product['cart_quantity'];
            }

            $shippingData[$idSellerinfo]['isCariersAvailable'] = false;
            foreach ($shipping['carriers'] as $carrier) {
                if (isset($carrier['available']) && $carrier['available'] == true) {
                    $shippingData[$idSellerinfo]['isCariersAvailable'] = true;
                }
            }

            $sellerCartCarrier = $sellerinfoCartCarrierRepository->findOneBy([
                'idSellerInfo' => $idSellerinfo,
                'idCart' => $this->context->cart->id,
            ]);

            $shippingData[$idSellerinfo]['selectedIdCarrierReference'] = $sellerCartCarrier
                ? $sellerCartCarrier->getIdCarrierReference() : null;

            if ($idSellerinfo == 0) {
                $shippingData[$idSellerinfo]['logoImageUrl'] =
                    _PS_IMG_ . \Configuration::get('PS_LOGO', null, null, (int) $this->context->shop->id);
                $shippingData[$idSellerinfo]['sellerLink'] = __PS_BASE_URI__;

                $shippingData[$idSellerinfo]['shop'] = new \stdClass();
                $shippingData[$idSellerinfo]['shop']->name =
                    \Configuration::get('PS_SHOP_NAME', null, null, (int) $this->context->shop->id);

                continue;
            }

            $sellerinfo = $sellerinfoRepository->find($idSellerinfo);
            $shippingData[$idSellerinfo]['sellerinfo'] = $sellerinfo;
            $shippingData[$idSellerinfo]['sellerinfoLang'] = $sellerinfoLangRepository->findOneBy([
                'sellerInfo' => $idSellerinfo,
                'lang' => $this->context->language->id,
            ]);

            $shippingData[$idSellerinfo]['shop'] = new \Shop($sellerinfo->getIdShop());
            $shippingData[$idSellerinfo]['logoImageUrl'] = AgileHelper::getImagePath($idSellerinfo, 'logo');
            $shippingData[$idSellerinfo]['sellerLink'] = AgileHelper::getSellerUrlByShopId($sellerinfo->getidShop());
        }

        $this->context->smarty->assign([
            'shippingData' => $shippingData,
            'image_size' => \ImageType::getFormattedName('medium'),
            'id_cart_sellershipping' => $this->context->cart->id,
            'freeMembershipEligibility' => AgileHelperMembership::showFreeMembershipEligibility($params),
        ]);

        return $this->context->smarty->fetch('module:agilemultisellerpro/views/templates/hook/shippingcheckoutstep.tpl');
    }

    protected function _hookDisplayShoppingCartFooter($params)
    {
        return AgileHelperMembership::showFreeMembershipEligibility($params);
    }

    protected function _hookActionValidateOrder($params)
    {
        $order = $params['order'];

        if (!\Validate::isLoadedObject($order)) {
            return;
        }

        $cart = new \Cart($order->id_cart);

        if (!\Validate::isLoadedObject($cart)) {
            return;
        }

        foreach ($cart->getProducts() as $product) {
            $sellerinfoProduct = $this->entityManager->getRepository(SellerinfoProduct::class)
                ->findOneBy(['idProduct' => (int) $product['id_product']]);

            if (!$sellerinfoProduct) {
                continue;
            }

            $sellerInfoOrder = $this->entityManager->getRepository(SellerinfoOrder::class)
                ->findOneBy(['sellerInfo' => $sellerinfoProduct->getSellerinfo(), 'idOrder' => $order->id]);

            if (!$sellerInfoOrder) {
                $sellerInfoOrder = new SellerinfoOrder();

                $sellerInfoOrder
                    ->setSellerinfo($sellerinfoProduct->getSellerinfo())
                    ->setIdOrder((int) $order->id);

                $this->entityManager->persist($sellerInfoOrder);
                $this->entityManager->flush();
            }
        }

        $ct_Ids = \Configuration::get(CommissionsDataConfiguration::ASC_CT_COMMISSION_AT);

        if (empty($ct_Ids)) {
            $ct_Ids = AgileHelper::getCommissionCreationDefaultStatuses();
        }

        $orderState = $params['orderStatus'];

        if (in_array($orderState->id, AgileHelper::stringIDsToArray($ct_Ids))) {
            $this->entityManager->getRepository(SellerinfoCommission::class)->createSellerCommission($order);
        }

        $orderDetaitls = $order->getOrderDetailList();
        foreach ($orderDetaitls as $detail) {
            $sellerinfoProduct = $this->entityManager->getRepository(SellerinfoProduct::class)
            ->findOneBy(['idProduct' => (int) $detail['product_id']]);

            if (!$sellerinfoProduct) {
                continue;
            }

            $sellerorderDetail = new SellerinfoOrderDetail();
            $sellerorderDetail->setIdOrderDetail($detail['id_order_detail']);
            $sellerorderDetail->setIdProduct($detail['product_id']);
            $sellerorderDetail->setSellerinfo($sellerinfoProduct->getSellerinfo());

            $this->entityManager->persist($sellerorderDetail);
            $this->entityManager->flush();
        }

        // create membership
        $this->createMembershipData($order->id, $orderState);
    }

    protected function _hookActionOrderStatusUpdate($params)
    {
        $rt_Ids = \Configuration::get(CommissionsDataConfiguration::ASC_RT_COMMISSION_AT);

        if (!$rt_Ids) {
            $rt_Ids = AgileHelper::getCommissionCancellationDefaultStatuses();
            $rt_Ids = AgileHelper::stringIDsToArray($rt_Ids);
        } else {
            $rt_Ids = json_decode($rt_Ids);
        }

        $ct_Ids = \Configuration::get(CommissionsDataConfiguration::ASC_CT_COMMISSION_AT);

        if (!$ct_Ids) {
            $ct_Ids = AgileHelper::getCommissionCreationDefaultStatuses();
            $ct_Ids = AgileHelper::stringIDsToArray($ct_Ids);
        } else {
            $ct_Ids = json_decode($ct_Ids);
        }

        $id_order = $params['id_order'];
        $order = new \Order($id_order);

        if (!\Validate::isLoadedObject($order)) {
            return;
        }

        $sellerinfoCommissionRepository = $this->entityManager->getRepository(SellerinfoCommission::class);

        if (in_array($params['newOrderStatus']->id, $rt_Ids)) {
            $sellerinfoCommissionRepository->cancelSellerCommission($order);
        } elseif (in_array($params['newOrderStatus']->id, $ct_Ids)) {
            $sellerinfoCommissionRepository->createSellerCommission($order);
        }

        $this->createMembershipData($id_order, $params['newOrderStatus']);
    }

    private function createMembershipData($idOrder, $orderState)
    {
        if (\Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_STATUS)) {
            $this->entityManager->getRepository(SellerinfoMembershipCustomer::class)
                ->createMembershipData($idOrder, $orderState);

            $sellerinfoMembershipHistories = $this->entityManager->getRepository(SellerinfoMembershipHistory::class)
                ->findBy([
                    'idOrder' => (int) $idOrder,
                ]);

            if ($sellerinfoMembershipHistories) {
                $idOrderState = (int) $orderState->id;
                foreach ($sellerinfoMembershipHistories as $sellerinfoMembershipHistory) {
                    $sellerinfoMembershipHistory->setIdOrderState($idOrderState);

                    $this->entityManager->persist($sellerinfoMembershipHistory);
                    $this->entityManager->flush();
                }
            }
        }
    }

    public function _hookActionCustomerAccountAdd($params)
    {
        if (
            (int) \Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_FREE_TRIAL_TIMING)
                == MembershipDataConfiguration::TIMING_NEW_CUSTOMER
        ) {
            AgileHelperMembership::createFreeMembership($params['newCustomer']);
        }
    }

    protected function _hookDisplayCustomerAccount()
    {
        $this->context->smarty->assign([
            'isSellerAccount' => (\Configuration::get('AGILE_MS_CUSTOMER_SELLER') || $this->isSeller()),
            'mysellerurl' => $this->context->link->getModuleLink('agilemultisellerpro', 'sellersummary', [], true),
            'feedbackwaitlistUrl' => $this->context->link->getModuleLink('agilemultisellerpro', 'feedbackwaitlist', [], true),
            'nbFeedbackWaiting' => $this->entityManager->getRepository(SellerinfoRating::class)
                ->getFeedbackWaitingCount($this->context->cookie->id_customer, true),
            'isMymembership' => $this->isMymembership(),
            'mymembershipUrl' => $this->context->link->getModuleLink('agilemultisellerpro', 'mymembership', [], true),
            'is',
        ]);

        return $this->context->smarty->fetch('module:agilemultisellerpro/views/templates/hook/customeraccount.tpl');
    }

    protected function _hookDisplayMyAccountBlock()
    {
        $this->context->smarty->assign([
            'isSellerActive' => $this->isSellerActive(),
            'feedbackwaitlistUrl' => $this->context->link->getModuleLink('agilemultisellerpro', 'feedbackwaitlist', [], true),
            'nbFeedbackWaiting' => $this->entityManager->getRepository(SellerinfoRating::class)
                ->getFeedbackWaitingCount($this->context->cookie->id_customer, true),
            'isMymembership' => $this->isMymembership(),
            'mymembershipUrl' => $this->context->link->getModuleLink('agilemultisellerpro', 'mymembership', [], true),
        ]);

        return $this->context->smarty->fetch('module:agilemultisellerpro/views/templates/hook/myaccount.tpl');
    }

    private function isMymembership()
    {
        return $this->isSellerActive() && \Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_STATUS);
    }

    protected function _hookDisplayTop()
    {
        return $this->context->smarty->fetch('module:agilemultisellerpro/views/templates/hook/displaytop.tpl');
    }

    protected function _hookDisplayProductExtraContent()
    {
        $res = [];

        if (\Configuration::get(DataConfiguration::AGILE_MS_SELLER_TAB) != 1) {
            return $res;
        }

        $sellerInfoProduct = $this->entityManager->getRepository(SellerinfoProduct::class)
            ->findOneBy(['idProduct' => (int) \Tools::getValue('id_product')]);

        if (!$sellerInfoProduct) {
            return $res;
        }

        $sellerinfo = $sellerInfoProduct->getSellerinfo();
        $sellerShop = \Shop::getShop($sellerinfo->getidShop());

        $sellerRating = $this->entityManager
            ->getRepository(SellerinfoRating::class)
            ->getAverageBySellerInfo($sellerinfo);

        $this->context->smarty->assign([
            'sellerInfo' => $sellerinfo,
            'sellerLink' => AgileHelper::getSellerUrlByShopId($sellerinfo->getidShop()),
            'sellerLogoUrl' => AgileHelper::getImagePath($sellerinfo->getIdSellerinfo(), 'logo'),
            'urls' => $this->context->controller->getTemplateVarUrls(),
            'sellerCountry' => \Country::getNameById($this->context->language->id, $sellerinfo->getIdCountry()),
            'sellerState' => \State::getNameById($sellerinfo->getIdState()),
            'sellerShop' => isset($sellerShop['name']) ? $sellerShop['name'] : '',
            'sellerRating' => $sellerRating,
            'sellerStars' => AgileHelperRating::getStarsImages($sellerRating),
        ]);

        $content = $this->context->smarty->fetch('module:agilemultisellerpro/views/templates/hook/displayextracontent.tpl');

        $res[] = (new \PrestaShop\PrestaShop\Core\Product\ProductExtraContent())
            ->setTitle($this->context->getTranslator()->trans('Seller info', [], 'Modules.Agilemultisellerpro.Hooks'))
            ->setContent($content);

        return $res;
    }

    protected function _hookActionEmailSendBefore($params)
    {
        if (
            !isset($params['templateVars']['{order_name}'])
            || !isset($params['templateVars']['{carrier}'])
        ) {
            return $params;
        }

        $idOrder = AgileHelper::getOrderIdFromMaildata($params['templateVars']);
        $idCart = \Order::getCartIdStatic($idOrder);

        if ((int) $idCart <= 0) {
            return $params;
        }

        $sellerCartCarriers = $this->entityManager->getRepository(SellerinfoCartCarrier::class)
            ->findBy([
                'idCart' => $idCart,
            ]);

        if ($sellerCartCarriers) {
            $sellerinfoLocationCarrierRepository = $this->entityManager->getRepository(SellerinfoLocationCarrier::class);
            $locations = [];

            foreach ($sellerCartCarriers as $cartCarrier) {
                $sellerinfoLocationCarrier = $sellerinfoLocationCarrierRepository
                    ->find($cartCarrier->getIdLocationCarrier());

                if ($sellerinfoLocationCarrier) {
                    $locations[] = $sellerinfoLocationCarrier->getLocation();
                }
            }

            if ($locations) {
                $params['templateVars']['{carrier}'] .= ': ' . implode('; ', $locations);
            }
        }

        return $params;
    }

    protected function _hookDisplayHeader($params)
    {
        if (AgileHelperMembership::isMemberOnlyContent($this->sellerinfo)) {
            \Tools::redirect($this->context->link->getModuleLink('agilemultisellerpro', 'accessdenied', [], true));
        }
    }

    protected function _hookActionCartSave($params)
    {
        if (
            !$this->isSeller()
            && \Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_STATUS)
            && !empty($params['cart'])
        ) {
            $errors = false;
            $cart = $params['cart'];

            foreach (AgileHelperMembership::getProductsByCart($cart->id) as $product) {
                if (AgileHelperMembership::isProductInMembershipCategory((int) $product['id_product'])) {
                    if (!$this->context->cart) {
                        $this->context->cart = new \Cart($cart->id);
                    }

                    if (!$this->context->currency) {
                        $this->context->currency = new \Currency($cart->id_currency);
                    }

                    $this->context->cart->deleteProduct((int) $product['id_product'], (int) $product['id_product_attribute']);

                    $productName = \Product::getProductName(
                        (int) $product['id_product'],
                        (int) $product['id_product_attribute']
                    );

                    $errors[] = $this->context->getTranslator()->trans(
                        'You are not allowed to purchase this product',
                        [],
                        'Modules.Agilemultisellerpro.Hooks'
                    ) . ': ' . $productName;
                }
            }

            if ($errors && \Tools::isSubmit('action')) {
                exit(json_encode([
                    'errors' => $errors,
                    'hasError' => true,
                ]));
            }
        }
    }

    protected function _hookActionProductGridDefinitionModifier($params)
    {
        if (version_compare(_PS_VERSION_, '8.1.0', '<')) {
            return;
        }

        $selelrRepository = \Module::getInstanceByName('agilemultisellerpro')->get('prestashop.module.agilemultisellerpro.repository.sellerinfo_repository');
        $sellers = [];
        if ($selelrRepository) {
            $sellers = $selelrRepository->getSellerInfos($this->context->language->id);
            $sellers = array_map(
                function ($seller) {
                    return [
                        'id' => $seller->getIdSellerinfo(),
                        'company' => $seller->getCompany(),
                    ];
                },
                $sellers
            );
            $sellers = array_combine(
                array_column($sellers, 'company'),
                array_column($sellers, 'id')
            );
        }

        $params['definition']
            ->getColumns()
            ->addAfter(
                'active',
                (new DataColumn('seller_name'))
                    ->setName($this->context->getTranslator()->trans('Seller', [], 'Modules.Agilemultisellerpro.Admin'))
                    ->setOptions([
                        'field' => 'seller_name',
                    ])
            )
        ;

        $params['definition']->getFilters()
            ->add(
                (new Filter('id_sellerinfo', ChoiceType::class))
                    ->setTypeOptions([
                        'required' => false,
                        'multiple' => false,
                        'placeholder' => $this->context->getTranslator()->trans('All', [], 'Admin.Global'),
                        'choices' => $sellers,
                    ])
                    ->setAssociatedColumn('seller_name')
            )
        ;
    }

    protected function _hookActionProductGridQueryBuilderModifier($params)
    {
        if (version_compare(_PS_VERSION_, '8.1.0', '<')) {
            return;
        }

        $params['count_query_builder']->leftJoin(
            'p',
            '`' . _DB_PREFIX_ . 'sellerinfo_product`',
            'sip',
            'sip.id_product = p.id_product'
        );
        $params['count_query_builder']->leftJoin(
            'sip',
            '`' . _DB_PREFIX_ . 'sellerinfo_lang`',
            'sel',
            'sel.id_sellerinfo = sip.id_sellerinfo AND sel.id_lang = ' . (int) $this->context->language->id
        );

        $params['search_query_builder']->leftJoin(
            'p',
            '`' . _DB_PREFIX_ . 'sellerinfo_product`',
            'sip',
            'sip.id_product = p.id_product'
        );
        $params['search_query_builder']->leftJoin(
            'sip',
            '`' . _DB_PREFIX_ . 'sellerinfo_lang`',
            'sel',
            'sel.id_sellerinfo = sip.id_sellerinfo AND sel.id_lang = ' . (int) $this->context->language->id
        );
        $params['search_query_builder']->addSelect('sip.id_sellerinfo');
        $params['search_query_builder']->addSelect('sel.company AS `seller_name`');

        foreach ($params['search_criteria']->getFilters() as $filterName => $filterValue) {
            if ($filterName == 'id_sellerinfo') {
                $sqlWhereGeneratedLangs = 'IFNULL(sip.id_sellerinfo, 0) = ' . (int) $filterValue;
                $params['count_query_builder']->andWhere($sqlWhereGeneratedLangs);
                $params['search_query_builder']->andWhere($sqlWhereGeneratedLangs);
            }
        }
    }

    /**
     * For prestashop 8.0.x
     */
    protected function _hookActionAdminProductsListingFieldsModifier($params)
    {
        if (\Tools::isSubmit('filter_column_id_seller')) {
            $id_seller = (int) \Tools::getValue('filter_column_id_seller', 0);
            if ($id_seller !== 0) {
                $this->context->cookie->filter_column_product_id_seller = $id_seller;
            } else {
                unset($this->context->cookie->filter_column_product_id_seller);
            }
        } elseif (\Tools::isSubmit('filter_column_id_product')) {
            unset($this->context->cookie->filter_column_product_id_seller);
        }

        if (!isset($params['sql_where'])) {
            return;
        }

        if (!$params['sql_where'] || count($params['sql_where']) >= 3) {
            foreach ($params['sql_where'] as &$condition) {
                if (is_string($condition) && trim($condition) == 'state = 1') {
                    $condition = 'p.' . $condition;
                    break;
                }
            }
            unset($condition);

            $params['sql_table']['sip'] = [
                'table' => 'sellerinfo_product',
                'join' => 'LEFT JOIN',
                'on' => 'sip.id_product = p.id_product',
            ];

            $params['sql_table']['sel'] = [
                'table' => 'sellerinfo_lang',
                'join' => 'LEFT JOIN',
                'on' => 'sel.id_sellerinfo = sip.id_sellerinfo AND sel.id_lang = ' . (int) $this->context->language->id,
            ];

            $params['sql_select']['id_seller'] = [
                'table' => 'sip',
                'field' => 'id_sellerinfo',
            ];
            $params['sql_select']['seller_name'] = [
                'table' => 'sel',
                'field' => 'company',
            ];

            if (isset($this->context->cookie->filter_column_product_id_seller)
                && $this->context->cookie->filter_column_product_id_seller !== '') {
                $params['sql_where'][] = 'sip.id_sellerinfo = ' . (int) $this->context->cookie->filter_column_product_id_seller;
            }
        }
    }

    public function _hookActionObjectProductUpdateAfter($params)
    {
        if (
            isset($params['object'])
            && !empty($params['object']->id)
            && $params['object']->id_category_default == \Configuration::get('AGILE_MEMBERSHIP_CID')
        ) {
            $idProduct = (int) $params['object']->id;

            $sellerinfoMembershipType = $this->entityManager
                ->getRepository(SellerinfoMembershipType::class)
                ->findOneBy(['idProduct' => $idProduct]);

            if (!$sellerinfoMembershipType) {
                $sellerinfoMembershipType = new SellerinfoMembershipType();

                $sellerinfoMembershipType->setIdProduct($idProduct);
                $sellerinfoMembershipType->setIdGroup((int) \Configuration::get('PS_CUSTOMER_GROUP'));

                $this->entityManager->persist($sellerinfoMembershipType);
                $this->entityManager->flush();
            }
        }
    }

    public function _hookActionObjectProductDeleteAfter($params)
    {
        if (isset($params['object']) && !empty($params['object']->id)) {
            $idProduct = (int) $params['object']->id;

            $sellerinfoMembershipType = $this->entityManager
                ->getRepository(SellerinfoMembershipType::class)
                ->findOneBy(['idProduct' => $idProduct]);

            if ($sellerinfoMembershipType) {
                $this->entityManager->remove($sellerinfoMembershipType);
                $this->entityManager->flush();
            }
        }
    }

    protected function _hookActionObjectOrderDetailDeleteAfter($params)
    {
        if (isset($params['object']) && !empty($params['object']->id)) {
            $idDetail = (int) $params['object']->id;

            $sellerinfoOrderDetail = $this->entityManager
                ->getRepository(SellerinfoOrderDetail::class)
                ->findOneBy(['idOrderDetail' => $idDetail]);

            if ($sellerinfoOrderDetail) {
                $this->entityManager->remove($sellerinfoOrderDetail);
                $this->entityManager->flush();
            }
        }
    }
}
