<?php

namespace App\Repository;

use App\Entity\Assetregister;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Pagerfanta\Pagerfanta;
use Doctrine\ORM\Query;
use Pagerfanta\Adapter\DoctrineORMAdapter;

/**
 * @method Assetregister|null find($id, $lockMode = null, $lockVersion = null)
 * @method Assetregister|null findOneBy(array $criteria, array $orderBy = null)
 * @method Assetregister[]    findAll()
 * @method Assetregister[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class AssetregisterRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Assetregister::class);
    }

    public function getAllAssetregisters(int $page = 1,  $tag ): Pagerfanta
    {
      // Create our query
      $query = $this->createQueryBuilder('r')
                    ->innerJoin('r.groups', 'g')
                    ->innerJoin('r.subgroup', 's')
                    ->innerJoin('r.assetname', 'a')
                    ->andWhere('g.name LIKE  :val')
                    ->orWhere('s.name LIKE  :val')
                    ->orWhere('a.name LIKE  :val')
                    ->orWhere('r.serialno LIKE  :val')
                    ->setParameter('val','%'.$tag.'%')
                    ->orderBy('r.id', 'DESC')
                    ->getQuery();
           

       // No need to manually get get the result ($query->getResult())

       // $paginator = $this->paginate($query, $currentPage);

         return $this->createPaginator($query, $page);
    }

    private function createPaginator(Query $query, int $page): Pagerfanta
    {
        $paginator = new Pagerfanta(new DoctrineORMAdapter($query));
        $paginator->setMaxPerPage(Assetregister::NUM_ITEMS);
        $paginator->setCurrentPage($page);

        return $paginator;
    }

    public function findLastObjAssetRegister(): ?Assetregister
    {
        return $this->createQueryBuilder('e')
            ->orderBy('e.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }

    // /**
    //  * @return Assetregister[] Returns an array of Assetregister objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('a')
            ->andWhere('a.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('a.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Assetregister
    {
        return $this->createQueryBuilder('a')
            ->andWhere('a.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}
