<?php

namespace App\Repository;

use App\Entity\Appreciation;
use App\Entity\Ministry;
use App\Entity\Programm;
use App\Entity\Action;
use App\Entity\Activity;
use App\Entity\Notation;
use App\Entity\Target;
use App\Entity\Goal;
use App\Entity\ActivityPTA;
use App\Entity\Mainstay;
use App\Entity\Accelerator;
use App\Entity\Costing;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

use Doctrine\ORM\EntityRepository;

/**
 * @method Ministry|null find($id, $lockMode = null, $lockVersion = null)
 * @method Ministry|null findOneBy(array $criteria, array $orderBy = null)
 * @method Ministry[]    findAll()
 * @method Ministry[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MinistryRepository extends ServiceEntityRepository
{
    private $session;

    public function __construct(SessionInterface $session, ManagerRegistry $registry)
    {
        parent::__construct($registry, Ministry::class);
        $this->session = $session;
    }

    public function ministryByYear($year) {
        $qb = $this->createQueryBuilder('m')
            ->where('m.years Like :year')
            ->setParameter('year', '%'.$year.'%')
            ->orderBy('m.code', 'ASC');
        return $qb->getQuery()->getResult();
    }

    public function findMinistryByYear($year, $ministry) {
        return $this->createQueryBuilder('m')
            ->andWhere('m.years Like :year')
            ->andWhere($ministry ? 'm.id = :ministry' : '1 = :val')
            ->setParameter('year', $year)
            ->setParameter($ministry ? 'ministry' : 'val', $ministry ? $ministry : 1) 
            ->orderBy('m.code', 'ASC')
        ;
    }
    
    public function getSensitivity($year, Goal $goal, ?Target $target)
    {        
        $whereClause = $target ? 't.id = :target' : 'g.id = :goal';
        $paramClause = $target ? 'target' : 'goal';
        $paramObject = $target ? $target : $goal;

        $qb = $this->createQueryBuilder('m')
            ->select('m.code')
            ->addSelect('m.name')
            ->addSelect('m.color')
            ->addSelect('SUM(n.sensitivity) AS sumSensitivity')
            ->addSelect('COUNT(n.activity) AS nbActivity')
            ->addSelect('SUM(CASE WHEN n.duplicated=false THEN y.amount ELSE 0 END) AS amount')

            ->innerJoin(Programm::class, 'p', Expr\Join::WITH, 'm.id = p.ministry')
            ->innerJoin(Action::class, 'a', Expr\Join::WITH, 'p.id = a.programm')
            ->innerJoin(Activity::class, 'y', Expr\Join::WITH, 'a.id = y.action')
            ->innerJoin(Notation::class, 'n', Expr\Join::WITH, 'y.id = n.activity')
            ->innerJoin(Target::class, 't', Expr\Join::WITH, 't.id = n.target')
            ->innerJoin(Goal::class, 'g', Expr\Join::WITH, 'g.id = t.goal')

            ->andWhere('n.sensitivity != 0')
            ->andWhere('a.year = :year')
            ->andWhere($whereClause)
            ->andWhere($this->session->get('_ministry') ? 'm.id= :ministry' : '1 = :ministry')

            ->setParameter('year', $year)
            ->setParameter($paramClause, $paramObject)
            ->setParameter('ministry', $this->session->get('_ministry') ? $this->session->get('_ministry') : 1)
            ->groupBy('m.id') 
            ->orderBy('m.id', 'ASC')
            ;

        $rows = $qb->getQuery()->getResult();

        foreach ($rows as $key => $row) {
            $rows[$key]['sensitivity'] = $rows[$key]['nbActivity'] ? round($rows[$key]['sumSensitivity'] / $rows[$key]['nbActivity'], 2) : 0;
            $appreciation = $this->getEntityManager()
                ->getRepository(Appreciation::class)
                ->findOneByValue($rows[$key]['sensitivity']);
            $rows[$key]['appreciation'] = $appreciation->getName();
            $rows[$key]['flag'] = $appreciation->getFlag();
        }

        return array_reverse($rows);
    }    
    
    public function getFinancialPTA($year, Mainstay $mainstay, ?Goal $goal)
    {
        $qb = $this->createQueryBuilder('m')
            ->select('m.code')
            ->addSelect('m.name')
            ->addSelect('m.color')
            ->addSelect('SUM(y.expectedCost) AS sumExpectedCost')
            ->addSelect('SUM(y.realizedCost) AS sumRealizedCost')
            ->addSelect('COUNT(y.id) AS nbActivity')
            
            ->innerJoin(ActivityPTA::class, 'y', Expr\Join::WITH, 'm.id = y.ministry')

            //->andWhere('y.executed = 1')
            ->andWhere('y.year = :year')
            ->andWhere('y.goal = :goal')
            ->setParameter('year', $year)
            ->setParameter('goal', $goal)
            ->groupBy('m.id') 
            ->orderBy('m.id', 'ASC')
            ;

        $rows = $qb->getQuery()->getResult();

        foreach ($rows as $key => $row) {
            $rows[$key]['rate'] = $rows[$key]['sumRealizedCost'] / $rows[$key]['sumExpectedCost'] * 100;
            /*$appreciation = $this->getEntityManager()
                ->getRepository(Appreciation::class)
                ->findOneByValue($rows[$key]['sensitivity']);
            $rows[$key]['appreciation'] = $appreciation->getName();
            $rows[$key]['flag'] = $appreciation->getFlag();*/
        }

        return array_reverse($rows);
    }    
}
