<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
    private QueryBuilder $qb;
    private array $order = ['firstname' => 'ASC', 'lastname' => 'ASC', 'createdAt' => 'ASC'];

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
        }

        $user->setPassword($newHashedPassword);
        $this->_em->persist($user);
        $this->_em->flush();
    }


    /**
     * Equivalent of FindAll()
     *
     * @return QueryBuilder
     */
    private function getQueryBuilder()
    {
        return $this->createQueryBuilder("u");
    }


    public function getAll()
    {
        $this->qb = $this->getQueryBuilder();
        return $this;
    }

    public function order(array $order)
    {
        $this->order = $order;
        return $this;
    }

    public function limit(int $limit)
    {
        $this->qb->setMaxResults($limit);
        return $this;
    }

    public function onlyValid()
    {
        $this->qb->andWhere('u.mainGroup IS NOT NULL');
        $this->qb->andWhere('u.mainRank IS NOT NULL');
        $this->qb->andWhere('u.isVerified = 1');
        $this->qb->andWhere('u.isDesactivated = 0');
        return $this;
    }

    public function search(?string $search, bool $adminmode = false)
    {
        if (null === $search) {
            return $this;
        }

        $this->qb->where('u.firstname LIKE :searchkey')
                ->orWhere('u.lastname LIKE :searchkey')
                ->orWhere('u.phone LIKE :searchkey')
                ->leftjoin('u.mainGroup', 'mg')
                ->orWhere('mg.shortName LIKE :searchkey')
                ->orWhere('mg.name LIKE :searchkey')
                ->leftjoin('u.mainRank', 'mr')
                ->orWhere('mr.shortname LIKE :searchkey')
                ->orWhere('mr.name LIKE :searchkey')
            ;

        if ($adminmode) {
            $this->qb->orWhere('u.email LIKE :searchkey');
        }

        $this->qb->setParameter('searchkey', '%' . $search . '%');

        return $this;
    }

    public function getResult()
    {
        if (false === is_null($this->order)) {
            foreach ($this->order as $key => $value) {
                if (strtoupper($value) != 'ASC' && strtoupper($value) != 'DESC') {
                    $key = $value;
                    $value = 'ASC';
                }
                if ($key === array_key_first($this->order)) {
                    $this->qb->orderBy('u.' . $key, $value);
                } else {
                    $this->qb->addorderBy('u.' . $key, $value);
                }
            }
        }

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