<?php

namespace UserBundle\Repository;

use Doctrine\ORM\EntityRepository;
use UserBundle\Entity\Subscription\OrganizationSubscription;

/**
 * OrganizationRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class OrganizationRepository extends EntityRepository
{

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function getListQueryBuilder()
    {
        $subDQL = $this->_em->createQueryBuilder()
            ->select('COUNT(_User.id)')
            ->from(OrganizationSubscription::class, '_Subscription')
            ->join('_Subscription.users', '_User')
            ->where('_Subscription.organization = Organization')
            ->getDQL();

        return $this->createQueryBuilder('Organization')
            ->select(
                'Organization.id, Organization.name',
                'COUNT(Subscription) as subscriptionCount',
                '('. $subDQL .') as usersCount'
            )
            ->leftJoin('Organization.subscriptions', 'Subscription')
            ->groupBy('Organization.id')
            ->orderBy('Organization.id');
    }
}
