<?php

namespace App\Repository;

use App\Entity\Orders;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * @extends ServiceEntityRepository<Orders>
 *
 * @method Orders|null find($id, $lockMode = null, $lockVersion = null)
 * @method Orders|null findOneBy(array $criteria, array $orderBy = null)
 * @method Orders[]    findAll()
 * @method Orders[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class OrdersRepository extends ServiceEntityRepository
{
    private ValidatorInterface $validator;

    public function __construct(ManagerRegistry $registry, ValidatorInterface $validator)
    {
        parent::__construct($registry, Orders::class);
        $this->validator = $validator;
    }

  /**
   * @param Orders $entity
   * @param bool $flush
   * @return void
   */
    public function add(Orders $entity, bool $flush = false): void
    {

        $errors = $this->validator->validate($entity);
        if (count($errors) > 0) {
            var_dump($errors);
        }

        $this->getEntityManager()->persist($entity);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

  /**
   * @param Orders $entity
   * @param bool $flush
   * @return void
   */
    public function update(Orders $entity, bool $flush = false): void
    {
        $order = $this->getEntityManager()->find(Orders::class, $entity->getId());

        if (!$order) {
            throw $this->createNotFoundException('Order not found: '.$entity->getId());
        }
    }

  /**
   * @param Orders $entity
   * @param bool $flush
   * @return void
   */
    public function remove(Orders $entity, bool $flush = false): void
    {
        $this->getEntityManager()->remove($entity);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * @return Orders[] Returns an array of Orders objects
     */
    public function findByStatus($status): array
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.status = :val')
            ->setParameter('val', $status)
            ->orderBy('o.id', 'ASC')
            ->setMaxResults(100)
            ->getQuery()
            ->getResult()
        ;
    }

    /**
     * @param $orderId
     * @return Orders|null
     * @throws \Doctrine\ORM\NonUniqueResultException
    */
    public function findOneByOrderId($orderId): ?Orders
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.order_id = :val')
            ->setParameter('val', $orderId)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
}
