<?php

namespace App\Repository;

use App\Entity\Menu;
use App\Entity\Zone;
use App\Entity\Schedule;
use App\Entity\Restaurant;
use Symfony\Component\Yaml\Yaml;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

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

    public function add(Restaurant $entity, bool $flush = false): void
    {
        $this->getEntityManager()->persist($entity);

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

    public function remove(Restaurant $entity, bool $flush = false): void
    {
        $this->getEntityManager()->remove($entity);

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

    /**
     * @return Restaurant[] Returns an array of Restaurant objects
     */
    public function listRestaurantApi($request): array
    {
        $pathConf = Yaml::parse(file_get_contents(realpath(__DIR__.'/../..') . '/config/services.yaml'));
        $url = $_ENV['BASE_URL_UPLOAD'] . $pathConf['parameters']['app.restaurant_image_uploads_path'];

        $query = $this->createQueryBuilder('r')
            ->select('r.id, r.name, r.timeFrom, r.timeTo, r.position,
            r.timeTo, CONCAT(\''.$url.'\',r.image) as image, r.isPickItUp, r.latitude, r.longitude,
            z.timezone, 0 as isOpen')
            ->leftJoin(
                Zone::class,
                'z',
                \Doctrine\ORM\Query\Expr\Join::WITH,
                'z.id = r.zone'
            )
            ->andWhere('r.isActive = 1')
            ->orderBy('r.position', 'ASC')
        ;

        if (!empty($request->get('latitude')) && !empty($request->get('longitude')))
        {
            $query = $query
                ->addSelect("GEO_DISTANCE('".$request->get('latitude')."', '".$request->get('longitude')."', r.latitude, r.longitude) AS distance")
                ->having('distance <= :distance')
                ->setParameter('distance', 10)
            ;
        }

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

    /**
     * @return Restaurant[] Returns an array of Restaurant objects
     */
    public function showRestaurantApi($id): array
    {
        $pathConf = Yaml::parse(file_get_contents(realpath(__DIR__.'/../..') . '/config/services.yaml'));
        $url = $_ENV['BASE_URL_UPLOAD'] . $pathConf['parameters']['app.menu_uploads_path'];

        $query = $this->createQueryBuilder('r')
            ->select('m.id, m.name, m.description, m.haveSize, m.haveExtra,
            CONCAT(\''.$url.'\',m.image) as image, m.pvp, 0 as size, 0 as extra')
            ->leftJoin(
                Menu::class,
                'm',
                \Doctrine\ORM\Query\Expr\Join::WITH,
                'm.restaurant = r.id'
            )
            ->andWhere('r.isActive = 1')
            ->andWhere('r.id = :id')
            ->setParameter('id', $id)

            ->orderBy('m.position, m.name', 'ASC')
        ;

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

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

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