<?php
namespace App\Service;

use App\Entity\PriceList;
use App\Repository\PriceListRepository;
use App\Repository\FilialRepository;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use App\Bundle\Infoclinica\Region;

class PriceListService
{
    private $priceListRepository;
    private $filialRepository;

    public function __construct(PriceListRepository $priceListRepository, FilialRepository $filialRepository)
    {
        $this->priceListRepository = $priceListRepository;
        $this->filialRepository = $filialRepository;
    }

    public function getFilteredPriceListQuery(array $filters): QueryBuilder
    {
        $filters['actual'] = true;

        if (empty($filters['filial'])) {
            $filters['filial'] = $this->getCurrentFilialIds();
        }

        $priceListQuery = $this->priceListRepository->createFilteredQueryBuilder($filters);
        
        return $priceListQuery;
    }

    public function getPriceListQuery(array $filters): QueryBuilder
    {
        $priceListQuery = $this->priceListRepository->createFilteredQueryBuilder($filters);
        
        return $priceListQuery;
    }

    private function getCurrentFilialIds(): array
    {
        $filials = $this->filialRepository->findByRegion(Region::getCurrentName());

        return array_map(function ($filial) {
            return $filial->getFid();
        }, $filials);
    }
}
