<?php

namespace App\Controller;

use App\Entity\Goal;
use App\Entity\Ministry;
use App\Entity\Commune;
use App\Entity\Department;
use App\Form\GoalSelType;
use App\Form\MinistrySelType;
use App\Form\MinistryCommuneType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

class GraphController extends AbstractController
{
    /**
     * @Route("/app/graph/global", name="app_graph_global")
     */
    public function graphGlobalAction(Request $request)
    {
        $barChart = []; 
        $year = $request->getSession()->get('_year');
        $datas=[];
        $type=null;

        $form = $this->createForm(MinistryCommuneType::class, null, [
            'sessionYear' => $request->getSession()->get('_year'),
            'sessionMinistry' => $request->getSession()->get('_ministry'),
            'sessionCommune' => $request->getSession()->get('_commune'),
            'sessionDepartement' => $request->getSession()->get('_departement'),
            'sessionType' => 'ministere',
        ]);

        $ministry = $this->getDoctrine()
        ->getRepository(Ministry::class)
        ->findOneBy(['id' => $request->getSession()->get('_ministry')]);
        $commune = $this->getDoctrine()
        ->getRepository(Commune::class)
        ->findOneBy(['id' => $request->getSession()->get('_commune')]);
        $departement = $this->getDoctrine()
        ->getRepository(Department::class)
        ->findOneBy(['id' => $request->getSession()->get('_departement')]);

        if($departement){
            $type='commune';
        }else{
            $type='ministere';
        }

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

            $previousType = $request->getSession()->get('previous_type');

            if ($type !== $previousType) {
                $form = $this->createForm(MinistryCommuneType::class, null, [
                    'sessionYear' => $request->getSession()->get('_year'),
                    'sessionMinistry' => $request->getSession()->get('_ministry'),
                    'sessionCommune' => $request->getSession()->get('_commune'),
                    'sessionDepartement' => $request->getSession()->get('_departement'),
                    'sessionType' => $type,
                    'sessionEntite' => null,
                ]);
            } 
            $request->getSession()->set('previous_type', $type);
            $request->getSession()->set('previous_entite', $entite);

        }

        $datas = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->getSensitivityGlobal($year, $type, $ministry, $commune, $departement);
        
        $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;
            }
        }
        
        /*foreach ($datas as $key => $data) {
            $barChart['labels'][] = 'ODD '.$datas[$key]['code'];
            $barChart['bgColor'][] = $datas[$key]['color'];
            $barChart['values'][] = $datas[$key]['sensitivity'];
        } */
        
        return $this->render('graph/graph_global.html.twig', [
            'barChart' => $barChart,
            'form' => $form->createView(),
            'type' => $type,
            'global' => $nombre ? $total/$nombre : 0
        ]);
    }

   /**
     * @Route("/app/graph/structure", name="app_graph_ministry")
     */
    public function graphMinistryAction(Request $request)
    {
        $datas = [];
        $programm=null;
        $action=null;


        $year = $request->getSession()->get('_year');

        if($request->getSession()->get('_ministry')){
            $datas = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->getSensitivityByMinistry($year, $request->getSession()->get('_ministry'), $programm, $action);
        }else if($request->getSession()->get('_commune')){
            $datas = $this->getDoctrine()
            ->getRepository(Goal::class)
            ->getSensitivityByCommune($year, $request->getSession()->get('_commune'), $programm, $action);
        }

        $form = $this->createForm(MinistrySelType::class, null, [
            'sessionYear' => $request->getSession()->get('_year'),
            'sessionMinistry' => $request->getSession()->get('_ministry'),
            'sessionCommune' => $request->getSession()->get('_commune'),
            'sessionDepartement' => $request->getSession()->get('_departement'),
        ]);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $programm = $form->get('programm')->getData();
            $action = $form->get('action')->getData();

            if($request->getSession()->get('_ministry')){
                $datas = $this->getDoctrine()
                ->getRepository(Goal::class)
                ->getSensitivityByMinistry($year, $request->getSession()->get('_ministry'), $programm, $action);
            }else if($request->getSession()->get('_commune')){
                $datas = $this->getDoctrine()
                ->getRepository(Goal::class)
                ->getSensitivityByCommune($year, $request->getSession()->get('_commune'), $programm, $action);
            }else{
                if($request->getSession()->get('_departement')){
                    $type="commune";
                }else{
                    $type = $form->get('type')->getData();
                }
                
                $entite = $form->get('entite')->getData();

                if($type=='ministere'){
                    $datas = $this->getDoctrine()
                    ->getRepository(Goal::class)
                    ->getSensitivityByMinistry($year, $entite, $programm, $action);
                }
                if($type=='commune'){
                    $datas = $this->getDoctrine()
                    ->getRepository(Goal::class)
                    ->getSensitivityByCommune($year, $entite, $programm, $action);
                }

            }
            
            foreach ($datas as $key => $data) {
                $datas[$key]['sensitivity'] = round($datas[$key]['sensitivity'], 2);
            } 
        }
        
        return $this->render('graph/graph_ministry.html.twig', [
            'datas' => $datas,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/graph/goal", name="app_graph_goal")
     */
    public function graphGoalAction(Request $request)
    {
        $datas = [];
        $datasCommunes = [];
        $year = $request->getSession()->get('_year');
        $type='ministere';
        $ministry=null;
        $commune=null;

        if($request->getSession()->get('_ministry')){
            $type='ministere';
            $ministry = $this->getDoctrine()->getRepository(Ministry::class)->findOneBy(['id' => $request->getSession()->get('_ministry')]);
        }

        if($request->getSession()->get('_commune')){
            $type='commune';
            $commune = $this->getDoctrine()->getRepository(Commune::class)->findOneBy(['id' => $request->getSession()->get('_commune')]);
        }

        if($request->getSession()->get('_departement')){
            $type='commune';
            $departement = $this->getDoctrine()->getRepository(Department::class)->findOneBy(['id' => $request->getSession()->get('_departement')]);
        }

        $form = $this->createForm(GoalSelType::class, null,[
            'sessionYear' => $request->getSession()->get('_year'),
            'sessionMinistry' => $request->getSession()->get('_ministry'),
            'sessionCommune' => $request->getSession()->get('_commune'),
            'sessionDepartement' => $request->getSession()->get('_departement'),
        ]);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            if($this->isGranted('ROLE_MANAGER')){
                $type = $form->get('type')->getData();
            }
            $goal = $form->get('goal')->getData();
            $target = $form->get('target')->getData();
            if($type=='ministere' && $goal){
                $datas = $this->getDoctrine()
                ->getRepository(Ministry::class)
                ->getSensitivity($year, $goal, $target);
            }
            
            if($type=='commune' && $goal){
                $datasCommunes = $this->getDoctrine()
                ->getRepository(Commune::class)
                ->getSensitivity($year, $goal, $target);
            }
            

            foreach ($datas as $key => $data) {
                $datas[$key]['sensitivity'] = round($datas[$key]['sensitivity'], 2);
            } 

            foreach ($datasCommunes as $key => $data) {
                $datasCommunes[$key]['sensitivity'] = round($datasCommunes[$key]['sensitivity'], 2);
                $datasCommunes[$key]['color'] = "#60235d";
            } 
        }

        return $this->render('graph/graph_goal.html.twig', [
            'datas' => $datas,
            'datasCommunes' => $datasCommunes,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/graph/cost", name="app_graph_cost")
     */
    public function graphCostAction(Request $request)
    {
        $donutChart = [];
        $programm = null;
        $action = null;
        $type = null;
        $datas =[];

        $ministry = $this->getDoctrine()
        ->getRepository(Ministry::class)
        ->findOneBy(['id' => $request->getSession()->get('_ministry')]);
        $commune = $this->getDoctrine()
        ->getRepository(Commune::class)
        ->findOneBy(['id' => $request->getSession()->get('_commune')]);
        $departement = $this->getDoctrine()
        ->getRepository(Department::class)
        ->findOneBy(['id' => $request->getSession()->get('_departement')]);


        $year = $request->getSession()->get('_year');

        $form = $this->createForm(MinistrySelType::class, null, [
            'sessionYear' => $request->getSession()->get('_year'),
            'sessionMinistry' => $request->getSession()->get('_ministry'),
            'sessionCommune' => $request->getSession()->get('_commune'),
            'sessionDepartement' => $request->getSession()->get('_departement'),
        ]);


        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            if ($this->isGranted('ROLE_MANAGER')) {
                $type = $form->get('type')->getData();
                $entite = $form->get('entite')->getData();
            }else if($this->isGranted('ROLE_DDD')){
                $type='commune';
                $entite = $form->get('entite')->getData();
            }
            if($type=='ministere') {
                $ministry = $entite;
            } else if($type=='commune') {
                $commune = $entite;
            }
            $programm = $form->get('programm')->getData();
            $action = $form->get('action')->getData();
        }
            $totalAmount = 0;
            $amounts = [];

            if($ministry){
                $datas = $this->getDoctrine()
                ->getRepository(Goal::class)
                ->getSensitivityByMinistry($year, $ministry, $programm, $action);
            }if($commune){
                $datas = $this->getDoctrine()
                ->getRepository(Goal::class)
                ->getSensitivityByCommune($year, $commune, $programm, $action);
            }

            foreach ($datas as $key => $data) {
                $donutChart['labels'][] = 'ODD '.$datas[$key]['code'];
                $donutChart['bgColor'][] = $datas[$key]['color'];
                $amounts[] = (int)$datas[$key]['amount'];
                $totalAmount += (int)$datas[$key]['amount'];
            }
        
            foreach ($amounts as $key => $amount) {
                $donutChart['percents'][] = round(($amount / $totalAmount)  * 100, 2);
            }

        return $this->render('graph/graph_cost.html.twig', [
            'donutChart' => $donutChart,
            'type' => $type,
            'form' => $form->createView(),
        ]);
    }
}
