<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\PickupOrder\Grid;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Query\QueryBuilder;
use PrestaShop\PrestaShop\Adapter\Shop\Context;
use PrestaShop\PrestaShop\Core\Grid\Query\AbstractDoctrineQueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Query\DoctrineSearchCriteriaApplicatorInterface;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;

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

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

    /**
     * @var Context
     */
    private $shopContext;

    public function __construct(Connection $connection, string $dbPrefix, DoctrineSearchCriteriaApplicatorInterface $searchCriteriaApplicator, Context $shopContext)
    {
        parent::__construct($connection, $dbPrefix);
        $this->searchCriteriaApplicator = $searchCriteriaApplicator;
        $this->shopContext = $shopContext;
    }

    public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        $queryBuilder = $this
            ->getCommonQueryBuilder($searchCriteria)
            ->select('po.*, GROUP_CONCAT(s.tracking_number) AS shipment_numbers, a.name AS pickup_address')
            ->groupBy('po.id');

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

        return $queryBuilder;
    }

    public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        return $this
            ->getCommonQueryBuilder($searchCriteria)
            ->select('COUNT(DISTINCT po.id)');
    }

    private function getCommonQueryBuilder(SearchCriteriaInterface $searchCriteria): QueryBuilder
    {
        $qb = $this->connection
            ->createQueryBuilder()
            ->from($this->dbPrefix . 'inpost_intl_pickup_order', 'po')
            ->innerJoin('po', $this->dbPrefix . 'inpost_intl_shipment', 's', 's.pickup_order_id = po.id')
            ->innerJoin('po', $this->dbPrefix . 'inpost_intl_pickup_address', 'a', 'a.id = po.pickup_address_id');

        $this->applyFilters($searchCriteria->getFilters(), $qb);

        if ($this->shopContext->isAllShopContext()) {
            return $qb;
        }

        return $qb
            ->innerJoin('s', $this->dbPrefix . 'orders', 'o', 'o.id_order = s.id_order')
            ->andWhere('o.id_shop IN (:shop_ids)')
            ->setParameter('shop_ids', $this->shopContext->getContextListShopID(), Connection::PARAM_INT_ARRAY);
    }

    /**
     * @param array<string, mixed> $filters
     */
    private function applyFilters(array $filters, QueryBuilder $qb): void
    {
        foreach ($filters as $filterName => $filterValue) {
            switch ($filterName) {
                case 'id':
                case 'pickup_address_id':
                    $qb->andWhere('po.' . $filterName . ' = :' . $filterName);
                    $qb->setParameter($filterName, $filterValue);

                    break;
                case 'tracking_number':
                    $qb->andWhere('po.' . $filterName . ' LIKE :' . $filterName);
                    $qb->setParameter($filterName, '%' . $filterValue . '%');

                    break;
                case 'created_at':
                    if (isset($filterValue['from'])) {
                        $qb->andWhere('po.' . $filterName . ' >= :' . $filterName . '_from');
                        $qb->setParameter($filterName . '_from', sprintf('%s 00:00:00', $filterValue['from']));
                    }

                    if (isset($filterValue['to'])) {
                        $qb->andWhere('po.' . $filterName . ' <= :' . $filterName . '_to');
                        $qb->setParameter($filterName . '_to', sprintf('%s 23:59:59', $filterValue['to']));
                    }

                    break;
                case 'is_sandbox':
                    $qb->andWhere('s.is_sandbox = :sandbox');
                    $qb->setParameter('sandbox', $filterValue, ParameterType::BOOLEAN);

                    break;
                case 'shipment_number':
                    $qb->andWhere('s.tracking_number LIKE :shipment_number');
                    $qb->setParameter('shipment_number', '%' . $filterValue . '%');

                    break;
                default:
                    break;
            }
        }
    }
}
