<?php

namespace App\Controller;

use App\Entity\Archive;
use App\Entity\Commune;
use App\Entity\Department;
use App\Entity\Desagregation;
use App\Entity\Document;
use App\Entity\Event;
use App\Entity\Goal;
use App\Entity\Indicator;
use App\Entity\Indice;
use App\Entity\Ministry;
use App\Entity\Rapport;
use App\Entity\Statut;
use App\Entity\Target;
use App\Entity\Year;
use App\Form\SensibiliteType;
use App\Utils\YearsUtils;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Service\SettingsManager;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

/**
 * @Route("/{_locale}", requirements={ "_locale": "%locale_regex%" })
 */
class FrontendController extends AbstractController
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    /**
     * @Route("/", name="index")
     */
    public function indexAction(Request $request, SettingsManager $settingsManager)
    {   
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();

        $year = $settingsManager->getLastYearRapport();

        $type='ministere';
        $ministry = null;
        $commune = null;

        $datas = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->getSensitivityGlobal($year, $type, $ministry, $commune, null);
        
        $total=0;
        $nombre=0;
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);
        foreach ($goals as $goal){
            $nombre++;
            $data = array_values(array_filter($datas, function($item) use ($goal) {
                return $item['code'] === $goal->getCode();
            }))[0] ?? null;
            if($data){
                $barChart['labels'][] = 'ODD '.$data['code'];
                $barChart['bgColor'][] = $data['color'];
                $barChart['values'][] = $data['sensitivity'];
                $total+=$data['sensitivity'];
            }else{
                $barChart['labels'][] = 'ODD '.$goal->getCode();
                $barChart['bgColor'][] = $goal->getColor();
                $barChart['values'][] = null;
            }
        }

        $events = $this->getDoctrine()->getRepository(Event::class)->findBy(['publie' => true],['date' => 'DESC']);

        return $this->render('frontend/index.html.twig', [
            'goals' => $goals,
            'events' => $events,
            'communes' => $communes,
            'year' => $year,
            'barChart' => $barChart,
        ]);
    }

    /**
     * @Route("/agenda2030", name="agenda2030")
     */
    public function agenda2030(SettingsManager $settingsManager)
    {
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);
        $year= $settingsManager->getLastYearRapport();

            $annees=[]; $data=[]; $colors=[];
            for($i=4; $i>=0;$i--){
                if($year-$i >= 2019){
                    $annees[]=$year-$i;
                    $data[]=round($settingsManager->getGlobalIndice($year-$i, $goals, 'rec', 1, null),2);
                    $colors[]='rgba(0, 143, 251, 0.85)';
                }
            }

            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';

            $annees[]='2030 (Cible)';
            $data[]=round($settingsManager->getGlobalIndice($year, $goals, 'maxValue', 1, null),2);
            $colors[]='#41B883';      

        return $this->render('frontend/agenda2030.html.twig', [
            'goals' => $goals,
            'annees' => $annees,
            'colors' => $colors,
            'data' => $data,
        ]);
    }

    /**
     * @Route("/agenda2063", name="agenda2063")
     */
    public function agenda2063()
    {
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2063]);

        return $this->render('frontend/agenda2063.html.twig', [
            'goals' => $goals,
        ]);
    }

    /**
     * @Route("/odd/{id}", name="odd")
     */
    public function indexGoalAction($id, Request $request, SettingsManager $settingsManager)
    {
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $status = $this->getDoctrine()->getRepository(Statut::class)->findAll();
        $year= $settingsManager->getLastYearRapport();

        $goal = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->findOneBy(['id' => $id]);

        $targets = $this->getDoctrine()
            ->getRepository(Target::class)
            ->findBy(['goal' => $id]);

            $year= $settingsManager->getLastYearRapport();
            $annees=[]; $data=[]; $colors=[];
            for($i=4; $i>=0;$i--){
                if($year-$i >= 2019){
                    $annees[]=$year-$i;
                    $data[]=round($settingsManager->getGoalIndice($year-$i, $goal, 'rec', 1, null),2);
                    $colors[]='rgba(0, 143, 251, 0.85)';
                }
            }

            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';

            $annees[]='2030 (Cible)';
            $data[]=round($settingsManager->getGoalIndice($year, $goal, 'maxValue', 1, null),2);
            $colors[]='#41B883';
        return $this->render('frontend/odd.html.twig', [
            'goals' => $goals,
            'goal' => $goal,
            'targets' => $targets,
            'departements' => $departements,
            'annees' => $annees,
            'colors' => $colors,
            'data' => $data,
            'status' => $status,
            'year' => $year,
        ]);
    }

    /**
     * @Route("/aspiration/{id}", name="aspiration")
     */
    public function aspiration($id, Request $request)
    {
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2063]);

        $goal = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->findOneBy(['id' => $id]);

        $targets = $this->getDoctrine()
            ->getRepository(Target::class)
            ->findBy(['goal' => $id]);

        return $this->render('frontend/aspiration.html.twig', [
            'goals' => $goals,
            'goal' => $goal,
            'targets' => $targets,
        ]);
    }

    /**
     * @Route("/cible/{id}", name="cible")
     */
    public function indexTargetAction($id, Request $request, SettingsManager $settingsManager)
    {
        $target = $this->getDoctrine()->getRepository(Target::class)->findOneBy(['id' => $id]);
        $goal=$target->getGoal();
        $targets=$goal->getTargets();
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $status = $this->getDoctrine()->getRepository(Statut::class)->findAll();
        $year= $settingsManager->getLastYearRapport();
            $annees=[]; $data=[];
            for($i=4; $i>=0;$i--){
                if($year-$i >= 2019){
                $annees[]=$year-$i;
                $data[]=round($settingsManager->getTargetIndice($year-$i, $target, 'rec', 1, null),2);
                $colors[]='rgba(0, 143, 251, 0.85)';
                }
            }
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';

            $annees[]='2030 (Cible)';
            $data[]=round($settingsManager->getTargetIndice($year, $target, 'maxValue', 1, null),2);
            $colors[]='#41B883';
        if($goal->getAgenda()==2063){
            return $this->render('frontend/cible2063.html.twig', [
                'goal' => $goal,
                'target' => $target,
                'targets' => $targets,
                'departements' => $departements,
                'status' => $status,
                'annees' => $annees,
                'colors' => $colors,
                'year' => $year,
                'data' => $data,
                'status' => $status,
                'agenda' => $goal->getAgenda(),
            ]);

        }else{
            return $this->render('frontend/cible.html.twig', [
                'goal' => $goal,
                'target' => $target,
                'targets' => $targets,
                'departements' => $departements,
                'status' => $status,
                'annees' => $annees,
                'colors' => $colors,
                'year' => $year,
                'data' => $data,
                'status' => $status,
                'agenda' => $goal->getAgenda(),
            ]);
        }
        
    }

    /**
     * @Route("/selectodd/{id}", name="selectodd")
     */
    public function selectodd($id)
    {
        $goal = $this->getDoctrine()->getRepository(Goal::class)->findOneBy(['id' => $id]);
        $indicateur = $goal->getTargets()[0]->getIndicators()[0];
        return $this->redirectToRoute('indicateur', ['id' => $indicateur->getId()]);
    }

    /**
     * @Route("/indicateur/{id}", name="indicateur")
     */
    public function indicateur(SettingsManager $settingsManager, $id)
    {
        $indicateur = $this->getDoctrine()->getRepository(Indicator::class)->findOneBy(['id' => $id]);
        $goal=$indicateur->getTarget()->getGoal();
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        $status = $this->getDoctrine()->getRepository(Statut::class)->findAll();
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => '2030']);
        $year= $settingsManager->getLastYearRapport();

        /*$goal = $this->getDoctrine()->getRepository(Goal::class)->findOneBy(['id' => $odd==0 ? 1 : $odd]);
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        $status = $this->getDoctrine()->getRepository(Statut::class)->findAll();
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findAll();
        $indicateur = $goal->getTargets()[0]->getIndicators()[0];
        $year= $settingsManager->getLastYearRapport();*/

            $annees=[]; $data=[];
            for($i=4; $i>=0;$i--){
                if($year-$i >= 2019){
                $annees[]=$year-$i;
                $data[]=round($settingsManager->getValeurIndicateur($year-$i, $indicateur, 1, null),2);
                $colors[]='rgba(0, 143, 251, 0.85)';
                }
            }
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';
            $annees[]='';
            $data[]=0;
            $colors[]='rgba(0, 143, 251, 0.85)';

            $annees[]='2030 (Cible)';
            $data[]=round($settingsManager->getIndicatorIndice($year, $indicateur, 'maxValue', 1, null),2);
            $colors[]='#41B883';

        return $this->render('frontend/indicateur.html.twig', [
            'departements' => $departements,
            'communes' => $communes,
            'id' => $id,
            'goals' => $goals,
            'colors' => $colors,
            'indicateur' => $indicateur,
            'year' => $year,
            'annees' => $annees,
            'data' => $data,
            'status' => $status,
        ]);
    }

    /**
     * @Route("/ministeres", name="ministeres")
     */
    public function ministeres(SettingsManager $settingsManager)
    {
        
        $ministeres = $this->getDoctrine()->getRepository(Ministry::class)->MinistryByYear($settingsManager->getLastYear());
        $indicatorsinstad = $this->getDoctrine()->getRepository(Indicator::class)->findBy(['communal' => false, 'instad' => true]);
        return $this->render('frontend/ministeres.html.twig', [
            'ministeres' => $ministeres,
            'indicatorsinstad' => $indicatorsinstad
        ]);
    }

    /**
     * @Route("/ministere/{id}", name="ministere")
     */
    public function ministere($id)
    {
        $ministere = $this->getDoctrine()->getRepository(Ministry::class)->find($id);

        return $this->render('frontend/ministere.html.twig', [
            'ministere' => $ministere
        ]);
    }

    /**
     * @Route("/communes", name="communes")
     */
    public function communes()
    {
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        $indicators = $this->getDoctrine()->getRepository(Indicator::class)->findBy(['communal' => true]);

        return $this->render('frontend/communes.html.twig', [
            'departements' => $departements,
            'communes' => $communes,
            'indicators' => $indicators,
        ]);
    }

    /**
     * @Route("/indicateur/chargerCommunes/{id}/{ind}", name="chargerCommunes")
     */
    public function chargerCommunes($id, $ind=0, SettingsManager $settingsManager)
    {
        $departement = $this->getDoctrine()->getRepository(Department::class)->findOneBy(['id' => $id]);
        $communes = $departement->getCommunes();
        $year= $settingsManager->getLastYearRapport();
        $indicateur = $this->getDoctrine()->getRepository(Indicator::class)->find($ind);

        return $this->render('frontend/charger_communes.html.twig', [
            'communes' => $communes,
            'departement' => $departement,
            'year' => $year,
            'indicateur' => $indicateur,
        ]);
    }

    /**
     * @Route("/indicateurs/chargerCommunes2/{id}", name="chargerCommunes2")
     */
    public function chargerCommunes2($id)
    {
        $departement = $this->getDoctrine()->getRepository(Department::class)->findOneBy(['id' => $id]);
        $communes = $departement->getCommunes();

        return $this->render('frontend/charger_communes2.html.twig', [
            'communes' => $communes,
            'departement' => $departement,
        ]);
    }

    /**
     * @Route("/commune/{id}", name="commune")
     */
    public function commune($id, SettingsManager $settingsManager)
    {
        $year= $settingsManager->getLastYearRapport();
        $commune = $this->getDoctrine()->getRepository(Commune::class)->findOneBy(['id' => $id]);
        $indicators = $this->getDoctrine()->getRepository(Indicator::class)->findBy(['communal' => true]);
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        $odds = $this->getDoctrine()->getRepository(Goal::class)->findAll();

        return $this->render('frontend/commune.html.twig', [
            'commune' => $commune,
            'communes' => $communes,
            'indicators' => $indicators,
            'odds' => $odds,
            'year' => $year,
        ]);
    }

    /**
     * @Route("/commune/donnees/{id}", name="download_commune")
     */
    public function download_commune($id, SettingsManager $settingsManager)
    {
        $year= $settingsManager->getLastYearRapport();
        $commune = $this->getDoctrine()->getRepository(Commune::class)->findOneBy(['id' => $id]);

        $maquette= $this->getParameter('kernel.project_dir') . '/public/upload/communes/download.xlsx';
        //Chargement de la maquette de base
        $spreadsheet = IOFactory::load($maquette);

        $sheet = $spreadsheet->getSheet(0);
        $sheet->setCellValue('C3', $year-4);
        $sheet->setCellValue('D3', $year-3);
        $sheet->setCellValue('E3', $year-2);
        $sheet->setCellValue('F3', $year-1);
        $sheet->setCellValue('G3', $year);

        $queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder();
        $queryBuilder->select(array('i'))
            ->from(Indicator::class, 'i')
            ->andWhere('i.communal = :communal')
            ->orderBy('i.id')
            ->setParameter('communal', true);
        $indicators = $queryBuilder->getQuery()->getScalarResult();

        $line=4;
        foreach ($indicators as $indicator) {
            $sheet->setCellValue('A1', $commune->getName().' - '.$year);
            $sheet->setCellValue('A'.$line, $indicator['i_code']);
            $sheet->setCellValue('B'.$line, $indicator['i_name']);
            $sheet->setCellValue('C'.$line, $settingsManager->getIndiceCommune($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year-4)));
            $sheet->setCellValue('D'.$line, $settingsManager->getIndiceCommune($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year-3)));
            $sheet->setCellValue('E'.$line, $settingsManager->getIndiceCommune($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year-2)));
            $sheet->setCellValue('F'.$line, $settingsManager->getIndiceCommune($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year-1)));
            $sheet->setCellValue('G'.$line, $settingsManager->getIndiceCommune($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year)));
            $sheet->setCellValue('H'.$line, $settingsManager->getIndiceCommuneObservation($commune, $settingsManager->getIndicateur($indicator['i_id']) , $settingsManager->getYear($year)));
            $line++;
        }

        //Télécharchement du fichier
        $fileName=$commune->getName().'-ODD-'.$year.'.xlsx';
        $writer = new Xlsx($spreadsheet);
        $response =  new StreamedResponse(
            function () use ($writer) {
                $writer->save('php://output');
            }
        );
        $response->headers->set('Content-Type', 'application/vnd.ms-excel');
        $response->headers->set('Content-Disposition', 'attachment;filename="'.$fileName.'"');
        $response->headers->set('Cache-Control','max-age=0');
        return $response;
    }

    /**
     * @Route("/evenements", name="evenements")
     */
    public function evenements()
    {
        $events = $this->getDoctrine()->getRepository(Event::class)->findBy(['publie' => true],['date' => 'DESC']);
        $evenements=array_chunk($events, 5);
        return $this->render('frontend/evenements.html.twig', [
            'evenements' => $evenements,
        ]);
    }

    /**
     * @Route("/evenement/{id}", name="evenement")
     */
    public function evenement($id)
    {
        $event = $this->getDoctrine()->getRepository(Event::class)->findOneBy(['id' => $id]);
        $events = $this->getDoctrine()->getRepository(Event::class)->findBy(['publie' => true]);
        shuffle($events);
        return $this->render('frontend/evenement.html.twig', [
            'event' => $event,
            'events' => $events,
        ]);
    }

    /**
     * @Route("/ptfs", name="ptfs")
     */
    public function ptfs()
    {
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);

        return $this->render('frontend/ptfs.html.twig', [
            'goals' => $goals,
        ]);
    }

    /**
     * @Route("/secteur-prive", name="secteur-prive")
     */
    public function secteurprive()
    {
        return $this->render('frontend/secteur-prive.html.twig', [
        ]);
    }

    /**
     * @Route("/parlementaires", name="parlementaires")
     */
    public function parlementaires()
    {
        return $this->render('frontend/parlementaires.html.twig', [
        ]);
    }

    /**
     * @Route("/universitaires", name="universitaires")
     */
    public function universitaires()
    {
        return $this->render('frontend/universitaires.html.twig', [
        ]);
    }

    /**
     * @Route("/osc", name="osc")
     */
    public function osc()
    {
        return $this->render('frontend/osc.html.twig', [
        ]);
    }


    /**
     * @Route("/actions-prioritaires", name="actionsprioritaires")
     */
    public function actionsprioritaires()
    {
        return $this->render('frontend/actionsprioritaires.html.twig', [
        ]);
    }

    /**
     * @Route("/actions-fort-impact-odd", name="actionsfortimpact")
     */
    public function actionsfortimpact()
    {
        return $this->render('frontend/actionsfortimpact.html.twig', [
        ]);
    }

    /**
     * @Route("/normes", name="normes")
     */
    public function normes()
    {
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        //dd($communes);
        return $this->render('frontend/normes.html.twig', [
            'departements' => $departements,
            'communes' => $communes,
        ]);
    }

    /**
     * @Route("/projets-fort-impact-odd", name="projetfortimpact")
     */
    public function projetsfortimpact()
    {
        return $this->render('frontend/projetsfortimpact.html.twig', [
        ]);
    }

    /**
     * @Route("/dgcs-odd", name="dgcsodd")
     */
    public function dgcsodd()
    {
        return $this->render('frontend/dgcsodd.html.twig', [
        ]);
    }

    /**
     * @Route("/contact", name="contact")
     */
    public function contact()
    {
        return $this->render('frontend/contact.html.twig', [
        ]);
    }

     /**
     * @Route("/documents", name="documents")
     */
    public function documents()
    {
        $documents = $this->getDoctrine()->getRepository(Document::class)->findBy(['published' => true]);
        return $this->render('frontend/documents.html.twig', [
            'documents' => $documents,
        ]);
    }

     /**
     * @Route("/rapports", name="rapports")
     */
    public function rapport()
    {
        $rapports = $this->getDoctrine()->getRepository(Year::class)->findBy(['rapport' => true]);
        return $this->render('frontend/rapports.html.twig', [
            'rapports' => $rapports,
        ]);
    }

     /**
     * @Route("/download", name="download")
     */
    public function download(SettingsManager $settingsManager)
    {
        $year= $settingsManager->getLastYearRapport();
        
        $ministeres = $this->getDoctrine()->getRepository(Ministry::class)->ministryByYear($year);

        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        return $this->render('frontend/download.html.twig', [
            'ministeres' => $ministeres,
            'communes' => $communes,
            'year' => $year
        ]);
    }

    /**
     * @Route("/aleatoire", name="aleatoire")
     */
    public function aleatoire()
    {
        $indicateurs = $this->getDoctrine()->getRepository(Indicator::class)->findAll();
        $departements = $this->getDoctrine()->getRepository(Department::class)->findAll();
        $communes = $this->getDoctrine()->getRepository(Commune::class)->findAll();
        foreach ($indicateurs as $indicateur) {
            if($indicateur->getId()<=255){
            foreach ($departements as $departement) {
                $value=($indicateur->getMaxValue() + $indicateur->getMinValue())/rand(2,4);
                $indice= new Indice();
                $indice->setIndicator($indicateur);
                $indice->setYear(2022);
                $indice->setValue($value);
                $indice->setMinValue($indicateur->getMinValue());
                $indice->setMaxValue($indicateur->getMaxValue());
                $indice->setRefValue($indicateur->getRefValue());
                $indice->setRefYear($indicateur->getRefYear());
                $indice->setDesagregation($this->getDoctrine()->getRepository(Desagregation::class)->find(2));
                $indice->setModalite($departement->getId());
                $this->getDoctrine()->getManager()->persist($indice);
            }
            foreach ($communes as $commune) {
                $value=($indicateur->getMaxValue () + $indicateur->getMinValue())/rand(2,4);
                $indice= new Indice();
                $indice->setIndicator($indicateur);
                $indice->setYear(2022);
                $indice->setValue($value);
                $indice->setMinValue($indicateur->getMinValue());
                $indice->setMaxValue($indicateur->getMaxValue());
                $indice->setRefValue($indicateur->getRefValue());
                $indice->setRefYear($indicateur->getRefYear());
                $indice->setDesagregation($this->getDoctrine()->getRepository(Desagregation::class)->find(3));
                $indice->setModalite($commune->getId());
                $this->getDoctrine()->getManager()->persist($indice);
            }
            $this->getDoctrine()->getManager()->flush();
        }


        }
        
        
        dd('Fin de la génération aléatoire');

        return $this->render('frontend/index.html.twig', [
        ]);
    }

    /**
     * @Route("/team", name="team")
     */
    public function teamAction()
    {
        return $this->render('index/team.html.twig', [
        ]);
    }

    /**
     * @Route("/maintenance", name="maintenance")
     */
    public function maintenanceAction()
    {
        return $this->render('frontend/maintenance.html.twig', [
        ]);
    }



   /**
     * @Route("/apps", name="app_apps")
     */
    public function appsAction(Request $request)
    {
        
        if($this->isGranted('ROLE_INSTAD')){
            $request->getSession()->set('_application', 1);
            return $this->redirectToRoute('app_suiodd_dashboard');
        }

        return $this->render('apps.html.twig', [
        ]);
    }

    /**
     * @Route("/fnodd", name="fnodd")
     */
    public function fnoddAction(Request $request)
    {
        
        return $this->render('frontend/fnodd.html.twig', [
        ]);
    }

    /**
     * @Route("/sensibilite-pta", name="sensibilite-pta")
     */
    public function sensibilitedAction(Request $request, SettingsManager $settingsManager)
    {
        $barChart = []; 
        $datas=[];
        $type='ministere';
        $ministry = null;
        $commune = null;
        $year = $settingsManager->getLastYearRapportPTA();

        $form = $this->createForm(SensibiliteType::class, null, [
            'annee' => $settingsManager->getYear($year),
        ]);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $year = $form->get('year')->getData()->getName();
            $type = $form->get('type')->getData();
            $entite = $form->get('entite')->getData();
            if($type=='ministere') {
                $ministry = $entite;
            } else if($type=='commune') {
                $commune = $entite;
            }
        }

        $datas = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->getSensitivityGlobal($year, $type, $ministry, $commune, null);
        
        $total=0;
        $nombre=0;
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2030]);
        foreach ($goals as $goal){
            $nombre++;
            $data = array_values(array_filter($datas, function($item) use ($goal) {
                return $item['code'] === $goal->getCode();
            }))[0] ?? null;
            if($data){
                $barChart['labels'][] = 'ODD '.$data['code'];
                $barChart['bgColor'][] = $data['color'];
                $barChart['values'][] = $data['sensitivity'];
                $total+=$data['sensitivity'];
            }else{
                $barChart['labels'][] = 'ODD '.$goal->getCode();
                $barChart['bgColor'][] = $goal->getColor();
                $barChart['values'][] = null;
            }
        }
        return $this->render('frontend/sensibilite.html.twig', [
            'form' => $form->createView(),
            'barChart' => $barChart,
            'year' => $year,
        ]);
    }


}