<?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
 */
declare(strict_types=1);

namespace PrestaShop\Module\AgileMultisellerPro\Grid\SellerMembershipsTypes;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\Membership\DataConfiguration;
use PrestaShop\PrestaShop\Core\Grid\Query\AbstractDoctrineQueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Query\DoctrineSearchCriteriaApplicatorInterface as DSCAInterface;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;

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

class AgileQueryBuilder extends AbstractDoctrineQueryBuilder
{
    /**
     * @var DoctrineSearchCriteriaApplicatorInterface
     */
    private $searchCriteriaApplicator;

    /**
     * @var int
     */
    private $languageId;

    /**
     * @param Connection $connection
     * @param string $dbPrefix
     * @param DoctrineSearchCriteriaApplicatorInterface $searchCriteriaApplicator
     * @param int $languageId
     */
    public function __construct(Connection $connection, $dbPrefix, DSCAInterface $searchCriteriaApplicator, $languageId)
    {
        parent::__construct($connection, $dbPrefix);

        $this->searchCriteriaApplicator = $searchCriteriaApplicator;
        $this->languageId = $languageId;
    }

    /**
     * {@inheritdoc}
     */
    public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria)
    {
        $qb = $this->getQueryBuilder($searchCriteria->getFilters());
        $qb
            ->select('
                smt.id_membership_type,
                smt.interval_membership,
                smt.units,
                smt.listing_max,
                smt.product_images,
                p.price,
                p.active,
                pl.name AS membership_type,
                gl.name AS discount_group
            ')
            ->groupBy('smt.id_membership_type');

        $this->searchCriteriaApplicator
            ->applySorting($searchCriteria, $qb)
            ->applyPagination($searchCriteria, $qb)
        ;

        return $qb;
    }

    /**
     * {@inheritdoc}
     */
    public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria)
    {
        $qb = $this->getQueryBuilder($searchCriteria->getFilters())
            ->select('COUNT(DISTINCT smt.id_membership_type)');

        return $qb;
    }

    /**
     * Get generic query builder.
     *
     * @param array $filters
     *
     * @return QueryBuilder
     */
    private function getQueryBuilder(array $filters)
    {
        $allowedFilters = [
            'id_membership_type' => 'smt.`id_membership_type`',
            'membership_type' => 'pl.`name`',
            'discount_group' => 'smt.`id_group`',
            'listing_max' => 'smt.`listing_max`',
            'product_images' => 'smt.`product_images`',
            'active' => 'p.`active`',
        ];

        $qb = $this->connection
            ->createQueryBuilder()
            ->from($this->dbPrefix . 'sellerinfo_membership_type', 'smt')
            ->leftJoin('smt', $this->dbPrefix . 'product', 'p', 'smt.id_product = p.id_product')
            ->leftJoin('p', $this->dbPrefix . 'product_lang', 'pl', 'p.id_product = pl.id_product AND pl.id_lang = :language')
            ->leftJoin('p', $this->dbPrefix . 'category_product', 'cp', 'p.id_product = cp.id_product')
            ->leftJoin('smt', $this->dbPrefix . 'group_lang', 'gl', 'smt.id_group = gl.id_group AND gl.id_lang = :language')
            ->andWhere('cp.id_category = :categoryId')
            ->setParameter('language', $this->languageId)
            ->setParameter('categoryId', (int) \Configuration::get(DataConfiguration::AGILE_MEMBERSHIP_CID))
        ;

        foreach ($filters as $name => $value) {
            if (isset($allowedFilters[$name])) {
                $valueName = 'value' . $name;

                if ('membership_type' === $name) {
                    $qb->andWhere($allowedFilters[$name] . ' LIKE :' . $valueName);
                    $qb->setParameter($valueName, '%' . $value . '%');
                } else {
                    $qb->andWhere($allowedFilters[$name] . ' = :' . $valueName);
                    $qb->setParameter($valueName, $value);
                }
            }
        }

        return $qb;
    }
}
