<?php

namespace App\Twig;

use App\Entity\TypePrestataire;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Extension\AbstractExtension;

class StatsExtension extends AbstractExtension
{
    protected $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('showMlcStats', [$this, 'showMlcStats']),
        ];
    }

    public function showMlcStats($stats)
    {
        $class = '';
        switch ($stats) {
            case 'user':
                $class = 'App\Entity\User';
                break;
            case 'prestataire':
                $class = null;
                $typepresta = $this->em->getRepository(TypePrestataire::class)->findOneBySlug('prestataire');
                $query = $this->em->createQuery(
                    'SELECT count(distinct p.id)
                    FROM App\\Entity\\Prestataire p
                    WHERE p.enabled = true AND p.typeprestataire = :typepresta'
                )->setParameter('typepresta', $typepresta);

                $val = $query->getSingleScalarResult();
                break;
            case 'partenaire':
                $class = null;
                $typepresta = $this->em->getRepository(TypePrestataire::class)->findOneBySlug('partenaire');
                $query = $this->em->createQuery(
                    'SELECT count(distinct p.id)
                    FROM App\\Entity\\Prestataire p
                    WHERE p.enabled = true AND p.typeprestataire = :typepresta'
                )->setParameter('typepresta', $typepresta);

                $val = $query->getSingleScalarResult();
                break;
            case 'adherent':
                $class = 'App\Entity\Adherent';
                break;
            case 'comptoir':
                $class = 'App\Entity\Comptoir';
                break;
            case 'groupe':
                $class = 'App\Entity\Groupe';
                break;
        }
        if (!empty($class)) {
            $query2 = $this->em->createQuery(
                'SELECT count(distinct u.id)
                FROM ' . $class . ' u
                WHERE u.enabled = true'
            );

            $val = $query2->getSingleScalarResult();
        }

        return $val;
    }
}
