<?php

namespace App\Repository;

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

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

    public function getAllVendors(int $page = 1,  $tag ): Pagerfanta
    {
      // Create our query
      $query = $this->createQueryBuilder('c')
                    ->andWhere('c.name LIKE  :val')
                    ->orWhere('c.address LIKE  :val')
                    ->orWhere('c.mobileno LIKE  :val')
                    ->orWhere('c.email LIKE  :val')
                    ->setParameter('val','%'.$tag.'%')
                    ->orderBy('c.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(Vendor::NUM_ITEMS);
        $paginator->setCurrentPage($page);

        return $paginator;
    }


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

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