<?php

namespace App\Repository;

use App\Entity\PriceList;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\QueryBuilder;

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

    public function createFilteredQueryBuilder(array $filters): QueryBuilder
    {
        $qb = $this->createQueryBuilder('p')
            ->addOrderBy('p.filial, p.schname', 'ASC');
        
        if (!empty($filters['kodoper'])) {
            $kodoper = match (true) {
                is_array($filters['kodoper']) => array_filter(
                    array_map('trim', array_filter($filters['kodoper'], 'is_string')),
                    function($code) { return $code !== ''; }
                ),
                is_string($filters['kodoper']) && trim($filters['kodoper']) !== '' => [trim($filters['kodoper'])],
                default => []
            };
            
            if (!empty($kodoper)) {
                // Логируем значения kodoper для отладки
                error_log('PriceListRepository: filtering by kodoper=' . json_encode($kodoper));
                
                $qb->andWhere('p.kodoper IN (:codes)')
                   ->setParameter('codes', $kodoper);
            }
        }

        if (!empty($filters['schname']) && trim($filters['schname']) !== '') {
            $qb->andWhere($qb->expr()->like('LOWER(p.schname)', 'LOWER(:schname)'))
               ->setParameter('schname', '%' . trim($filters['schname']) . '%');
        }

        if (!empty($filters['filial'])) {
            $filialIds = match (true) {
                is_array($filters['filial']) => array_filter($filters['filial'], function($id) {
                    return $id !== null && $id !== '';
                }),
                is_string($filters['filial']) && $filters['filial'] !== '' => [$filters['filial']],
                is_numeric($filters['filial']) => [(int)$filters['filial']],
                default => []
            };

            if (!empty($filialIds)) {
                $qb->andWhere('p.filial IN (:filial)')
                    ->setParameter('filial', $filialIds);
            }
        }

        if (!empty($filters['actual'])) {
            if ($filters['actual']) {
                $qb->andWhere('p.dateUpdate >= :dateUpdate')
                    ->setParameter('dateUpdate', (new \DateTime())
                        ->modify('-2 day')
                        ->format('Y-m-d 00:00:00')
                    );
            }
        }

        if (!empty($filters['groupId'])) {
            $qb->andWhere('p.groupId = :groupId')
                ->setParameter('groupId', (int) $filters['groupId']);
        }

        return $qb;
    }
}
