<?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\Commune;
use App\Entity\Department;
use App\Entity\Notation;
use App\Entity\Target;
use App\Entity\Goal;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findProgrammByYear($year, $ministry, $commune) {
        $qb = $this->createQueryBuilder('p')
            ->andWhere('p.years LIKE :year')
            ->setParameter('year', $year)
            ->orderBy('p.code', 'ASC');

        if ($ministry) {
            $qb->andWhere('p.ministry = :ministry')
               ->setParameter('ministry', $ministry);
        } elseif ($commune) {
            $qb->andWhere('p.commune = :commune')
               ->setParameter('commune', $commune);
        } else {
            // Si ni ministère ni commune n'est sélectionné, retourner une requête vide
            $qb->andWhere('1 = 0');
        }

        return $qb;
    }

    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('p')
            ->select('p.code')
            ->addSelect('p.name')
            ->addSelect('IDENTITY(p.ministry) AS ministry')
            ->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(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('y.year = :year')
            ->andWhere($whereClause)
            ->andWhere('p.ministry IS NOT NULL')

            ->setParameter('year', $year)
            ->setParameter($paramClause, $paramObject)
            ->groupBy('p.id') 
            ->orderBy('p.id', 'ASC')
            ;

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

        foreach ($rows as $key => $row) {
            $rows[$key]['name'] = $rows[$key]['name'] . ' (' . $rows[$key]['code'] . ')'; 
            $rows[$key]['code'] = $this->getEntityManager()
                ->getRepository(Ministry::class)
                ->find($rows[$key]['ministry'])->getCode();
            $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 getSensitivityByCommune($year, Goal $goal, ?Target $target)
    {        
        $whereClause = $target ? 't.id = :target' : 'g.id = :goal';
        $paramClause = $target ? 'target' : 'goal';
        $paramObject = $target ? $target : $goal;

        $qb = $this->createQueryBuilder('p')
            ->select('p.code')
            ->addSelect('p.name')
            ->addSelect('IDENTITY(p.commune) AS commune')
            ->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(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('y.year = :year')
            ->andWhere($whereClause)
            ->andWhere('p.commune IS NOT NULL')

            ->setParameter('year', $year)
            ->setParameter($paramClause, $paramObject)
            ->groupBy('p.id') 
            ->orderBy('p.id', 'ASC')
            ;

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

        foreach ($rows as $key => $row) {
            $rows[$key]['name'] = $rows[$key]['name'] . ' (' . $rows[$key]['code'] . ')'; 
            $rows[$key]['code'] = $this->getEntityManager()
                ->getRepository(Commune::class)
                ->find($rows[$key]['commune'])->getName();
            $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 ? $appreciation->getName() : '-';
            $rows[$key]['flag'] = $appreciation ? $appreciation->getFlag() : 'red';
        }

        return array_reverse($rows);
    }

    public function getTotal($year, $type, ?Ministry $ministry, ?Commune $commune, ?Department $departement)
    { 
        return $this->createQueryBuilder('p')
            ->select('COUNT(p.id)')
            ->leftJoin('p.commune', 'c') 
            ->andWhere('p.years LIKE :year')
            ->andWhere($ministry ? 'p.ministry = :ministry' : '1 = :ministry')
            ->andWhere($commune ? 'p.commune = :commune' : '1 = :commune')
            ->andWhere($departement ? 'c.department = :department' : '1 = :department')
            ->andWhere(($type === 'ministere' || $ministry) ? 'p.ministry IS NOT NULL' : '1 = 1')
            ->andWhere(($type === 'commune' || $commune) ? 'p.commune IS NOT NULL' : '1 = 1')
            ->setParameter('year', '%'.$year.'%')
            ->setParameter('ministry', $ministry ? $ministry : 1)
            ->setParameter('commune', $commune ? $commune : 1)
            ->setParameter('department', $departement ? $departement : 1)
            ->getQuery()
            ->getSingleScalarResult();
    }
}
