<?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\SellerMemberships;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
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('
                smc.origin,
                smh.id_membership_history,
                smh.date_start,
                smh.expiry_date,
                IFNULL(smh.is_cancelled, 0) AS is_cancelled,
                o.id_order,
                c.firstname,
                c.lastname,
                c.email,
                IFNULL(od.product_name, pl.name) AS membership_type,
                osl.name AS order_state,
                os.color,
                od.product_price
            ');

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

        return $qb;
    }

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

        return $qb;
    }

    /**
     * Get generic query builder.
     *
     * @param array $filters
     *
     * @return QueryBuilder
     */
    private function getQueryBuilder(array $filters)
    {
        $allowedFilters = [
            'id_membership_history' => 'smh.`id_membership_history`',
            'id_order' => 'o.`id_order`',
            'firstname' => 'c.`firstname`',
            'lastname' => 'c.`lastname`',
            'email' => 'c.`email`',
            'membership_type' => 'pl.`name`',
            'order_state' => 'osl.`id_order_state`',
            'product_price' => 'od.`product_price`',
            'date_start' => 'smh.`date_start`',
            'expiry_date' => 'smh.`expiry_date`',
            'origin' => 'smc.`origin`',
            'is_cancelled' => 'smh.`is_cancelled`',
        ];

        $qb = $this->connection
            ->createQueryBuilder()
            ->from($this->dbPrefix . 'sellerinfo_membership_customer', 'smc')
            ->leftJoin('smc', $this->dbPrefix . 'customer', 'c', 'smc.id_customer = c.id_customer')
            ->leftJoin('c', $this->dbPrefix . 'sellerinfo_membership_history', 'smh', 'c.id_customer = smh.id_customer')
            ->leftJoin('smh', $this->dbPrefix . 'order_detail', 'od', 'smh.id_order = od.id_order AND smh.id_product = od.product_id AND smh.id_product_attribute = od.product_attribute_id')
            ->leftJoin('smh', $this->dbPrefix . 'order_state_lang', 'osl', 'smh.id_order_state = osl.id_order_state AND osl.id_lang = :language')
            ->leftJoin('smh', $this->dbPrefix . 'product_lang', 'pl', 'smh.id_product = pl.id_product AND pl.id_lang = :language AND pl.id_shop = :shop')
            ->leftJoin('od', $this->dbPrefix . 'orders', 'o', 'od.id_order = o.id_order')
            ->leftJoin('o', $this->dbPrefix . 'order_state', 'os', 'os.id_order_state = o.current_state')
            ->andWhere('smh.id_order > 0')
            ->setParameter('language', $this->languageId)
            ->setParameter('shop', (int) \Configuration::get('PS_SHOP_DEFAULT'))
        ;

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

                if (
                    'firstname' === $name
                    || 'lastname' === $name
                    || 'email' === $name
                    || 'membership_type' === $name
                ) {
                    $qb->andWhere($allowedFilters[$name] . ' LIKE :' . $valueName);
                    $qb->setParameter($valueName, '%' . $value . '%');
                } elseif ('date_start' === $name || 'expiry_date' === $name) {
                    if (isset($value['from'])) {
                        $qb->andWhere("{$allowedFilters[$name]} >= :{$valueName}From");
                        $qb->setParameter($valueName . 'From', $value['from'] . ' 00:00:00');
                    }
                    if (isset($value['to'])) {
                        $qb->andWhere("{$allowedFilters[$name]} <= :{$valueName}To");
                        $qb->setParameter($valueName . 'To', $value['to'] . ' 23:59:59');
                    }
                } else {
                    $qb->andWhere($allowedFilters[$name] . ' = :' . $valueName);
                    $qb->setParameter($valueName, $value);
                }
            }
        }

        return $qb;
    }
}
