<?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\Depot\Repository;

use CpCreation\VitiCore\Depot\Model\Depot;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @return array<int, Depot>
     */
    public function findByCategory(string $slug): array
    {
        return $this
            ->createQueryBuilder('depot')
            ->innerJoin('depot.translations', 'tr', Join::WITH, 'tr.translatable = depot.id')
            ->innerJoin('depot.category', 'ca', Join::WITH, 'ca.id = depot.category')
            ->innerJoin('ca.translations', 'catr', Join::WITH, 'catr.translatable = ca.id')
            ->andWhere('catr.slug = :slug')
            ->andWhere('depot.disabled = FALSE')
            ->orderBy('depot.postal', 'ASC')
            ->setParameter('slug', $slug)
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, Depot>
     */
    public function findByCategoryOrderName(string $slug): array
    {
        return $this
            ->createQueryBuilder('depot')
            ->innerJoin('depot.translations', 'tr', Join::WITH, 'tr.translatable = depot.id')
            ->innerJoin('depot.category', 'ca', Join::WITH, 'ca.id = depot.category')
            ->innerJoin('ca.translations', 'catr', Join::WITH, 'catr.translatable = ca.id')
            ->andWhere('catr.slug = :slug')
            ->andWhere('depot.disabled = FALSE')
            ->orderBy('tr.name', 'ASC')
            ->setParameter('slug', $slug)
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, Depot>
     */
    public function findAllOrderByCountryOrderByCategoryOrderPostalAll(): array
    {
        return $this
            ->createQueryBuilder('depot')
            ->leftJoin('depot.translations', 'tr')
            ->leftJoin('depot.category', 'ca')
            ->leftJoin('ca.translations', 'catr')
            ->addOrderBy('ca.position', 'ASC')
            ->addOrderBy('depot.country', 'ASC')
            ->addOrderBy('depot.postal', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, Depot>
     */
    public function findAllOrderByCountryOrderByCategoryOrderPosition(): array
    {
        return $this
            ->createQueryBuilder('depot')
            ->leftJoin('depot.translations', 'tr')
            ->leftJoin('depot.category', 'ca')
            ->leftJoin('ca.translations', 'catr')
            ->addOrderBy('ca.position', 'ASC')
            ->addOrderBy('depot.position', 'ASC')
            ->andWhere('depot.disabled = FALSE')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return array<int, Depot>
     */
    public function findAllOrderByCountryOrderByCategoryOrderPositionAdmin(): array
    {
        return $this->findAdminFiltered();
    }

    /**
     * @return array<int, Depot>
     */
    public function findAdminFiltered(
        ?string $search = null,
        ?string $categoryId = null,
        ?string $country = null,
        string $status = 'all',
    ): array {
        $qb = $this
            ->createQueryBuilder('depot')
            ->distinct()
            ->leftJoin('depot.translations', 'tr')
            ->leftJoin('depot.category', 'ca')
            ->leftJoin('ca.translations', 'catr')
            ->addSelect('ca.position AS HIDDEN categoryPosition')
            ->addOrderBy('categoryPosition', 'ASC')
            ->addOrderBy('depot.position', 'ASC')
            ->addOrderBy('depot.id', 'ASC');

        if (null !== $search) {
            $qb
                ->andWhere(<<<'DQL'
                    LOWER(COALESCE(tr.name, '')) LIKE :search
                    OR LOWER(COALESCE(tr.description, '')) LIKE :search
                    OR LOWER(COALESCE(catr.name, '')) LIKE :search
                    OR LOWER(COALESCE(depot.address, '')) LIKE :search
                    OR LOWER(COALESCE(depot.postal, '')) LIKE :search
                    OR LOWER(COALESCE(depot.city, '')) LIKE :search
                    OR LOWER(COALESCE(depot.country, '')) LIKE :search
                    DQL)
                ->setParameter('search', '%' . mb_strtolower(mb_trim($search)) . '%');
        }

        if ('__none__' === $categoryId) {
            $qb->andWhere('depot.category IS NULL');
        } elseif (null !== $categoryId) {
            $qb
                ->andWhere('ca.id = :categoryId')
                ->setParameter('categoryId', $categoryId);
        }

        if (null !== $country) {
            $qb
                ->andWhere('depot.country = :country')
                ->setParameter('country', $country);
        }

        if ('published' === $status) {
            $qb->andWhere('depot.disabled = FALSE');
        } elseif ('unpublished' === $status) {
            $qb->andWhere('depot.disabled = TRUE');
        }

        return $qb->getQuery()->getResult();
    }

    public function moveUpInCategory(Depot $depot): bool
    {
        $position = $depot->getPosition();

        if (null === $position || $position <= 0) {
            return false;
        }

        $previousDepot = $this->findOneBy([
            'category' => $depot->getCategory(),
            'position' => $position - 1,
        ]);

        if (!$previousDepot instanceof Depot) {
            return false;
        }

        $depot->setPosition($position - 1);
        $this->save($depot);

        return true;
    }

    public function moveDownInCategory(Depot $depot): bool
    {
        $position = $depot->getPosition();

        if (null === $position) {
            return false;
        }

        $nextDepot = $this->findOneBy([
            'category' => $depot->getCategory(),
            'position' => $position + 1,
        ]);

        if (!$nextDepot instanceof Depot) {
            return false;
        }

        $depot->setPosition($position + 1);
        $this->save($depot);

        return true;
    }
}
