<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Product\Repository;

use CpCreation\VitiCore\Product\Model\ProductPriceCode;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\Persistence\ManagerRegistry;

class ProductPriceCodeRepository extends BaseRepository
{
    private static ?\Transliterator $codeTransliterator = null;

    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ProductPriceCode::class);
    }

    /**
     * @return ProductPriceCode[]
     */
    public function findByGroupOrderAdmin(): array
    {
        return $this->createQueryBuilder('r')
            ->andWhere('r.deletedAt IS NULL')
            ->orderBy('r.group', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findOneCode(string $code): ?ProductPriceCode
    {
        return $this->findOneByUpperCode($code, true)
            ?? $this->findOneByNormalizedCode($code, true);
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findOneExistingCode(string $code): ?ProductPriceCode
    {
        return $this->findOneByUpperCode($code, false)
            ?? $this->findOneByNormalizedCode($code, false);
    }

    public static function normalizeCode(string $code): string
    {
        $code = mb_trim($code);

        if ('' === $code) {
            return '';
        }

        $normalizedCode = self::getCodeTransliterator()?->transliterate($code);

        if (\is_string($normalizedCode)) {
            $code = $normalizedCode;
        }

        return mb_strtoupper(mb_trim($code));
    }

    /**
     * @throws NonUniqueResultException
     */
    public function findOneViewHt(string $code): ?ProductPriceCode
    {
        return $this->createQueryBuilder('r')
            // À adapter selon le vrai nom du champ :
            // ->andWhere('r.viewHt = true')
            ->andWhere('r.code = :code')
            ->andWhere('r.deletedAt IS NULL')
            ->setParameter('code', $code)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @throws NonUniqueResultException
     */
    private function findOneByUpperCode(string $code, bool $enabledOnly): ?ProductPriceCode
    {
        $queryBuilder = $this->createQueryBuilder('r')
            ->andWhere('UPPER(r.code) = :code')
            ->andWhere('r.deletedAt IS NULL')
            ->setParameter('code', mb_strtoupper(mb_trim($code)))
            ->setMaxResults(1);

        if ($enabledOnly) {
            $queryBuilder->andWhere('r.disabled = false');
        }

        return $queryBuilder
            ->getQuery()
            ->getOneOrNullResult();
    }

    private function findOneByNormalizedCode(string $code, bool $enabledOnly): ?ProductPriceCode
    {
        $normalizedCode = self::normalizeCode($code);

        if ('' === $normalizedCode) {
            return null;
        }

        $queryBuilder = $this->createQueryBuilder('r')
            ->andWhere('r.deletedAt IS NULL')
            ->orderBy('r.code', 'ASC');

        if ($enabledOnly) {
            $queryBuilder->andWhere('r.disabled = false');
        }

        foreach ($queryBuilder->getQuery()->getResult() as $priceCode) {
            if (
                $priceCode instanceof ProductPriceCode
                && $normalizedCode === self::normalizeCode((string) $priceCode->getCode())
            ) {
                return $priceCode;
            }
        }

        return null;
    }

    private static function getCodeTransliterator(): ?\Transliterator
    {
        return self::$codeTransliterator ??= \Transliterator::createFromRules('::Latin-ASCII; ::Upper;');
    }
}
