<?php

namespace App\Controller;

use App\Entity\Desagregation;
use App\Entity\Goal;
use App\Entity\Target;
use App\Entity\Indicator;
use App\Entity\Modalite;
use App\Entity\Zone;
use App\Form\ZoneType;
use App\Form\GoalType;
use App\Form\DesagregationType;
use App\Form\TargetType;
use App\Form\IndicatorType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Utils\YearsUtils;

class GoalController extends AbstractController
{
    private $params;

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

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

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

    /**
     * @Route("/app/goal/new", name="app_goal_new")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newGoalAction(Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

        $goal = new Goal();
        $goals = $this->getDoctrine()->getRepository(Goal::class)->findBy(['agenda' => 2063]);

        $form = $this->createForm(GoalType::class, $goal);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $goal = $form->getData();
            $goal->setAgenda(2030);

            $this->getDoctrine()->getManagerForClass(Goal::class)->persist($goal);
            $this->getDoctrine()->getManagerForClass(Goal::class)->flush();

            $this->addFlash('success', 'ODD ajouté avec succès');
            return $this->redirectToRoute('app_goal_new');
        }

        return $this->render('goal/goal_form.html.twig', [
            'goal' => $goal,
            'goals' => $goals,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/goal/{id}", name="app_goal")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function goalAction($id, Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

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

        $form = $this->createForm(GoalType::class, $goal);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $goal = $form->getData();

            $alignementsarray = array();
            if ($request->get('alignements')) {
                foreach ($request->get('alignements') as $a) {
                    $v=array();
                    $v[]=$a['alignement'];
                    $v[]=$a['lien'];
                    $alignementsarray[]=$v;
                }
            }
            $goal->setAlignement($alignementsarray);

            $this->getDoctrine()->getManagerForClass(Goal::class)->flush();
            $this->addFlash('success', 'ODD modifié avec succès');
            return $this->redirectToRoute('app_goals');
        }

        return $this->render('goal/goal_form.html.twig', [
            'goal' => $goal,
            'goals' => $goals,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/goal/{id}/delete", name="app_goal_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function deleteGoalAction($id, Request $request)
    {
        try {
            $goal = $this->getDoctrine()->getRepository(Goal::class)->find($id);
            $this->getDoctrine()->getManager()->remove($goal);
            $this->getDoctrine()->getManager()->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_goals');
        }
        $this->addFlash('success', 'ODD supprimé avec succès');
        return $this->redirectToRoute('app_goals');
    }

    /**
     * @Route("/app/targets", name="app_targets")
     */
    public function targetsAction()
    {
        $targets = $this->getDoctrine()->getRepository(TArget::class)->findByAgenda(2030);

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

    /**
     * @Route("/app/target/new", name="app_target_new")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newTargetAction(Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

        $target = new Target();

        $form = $this->createForm(TargetType::class, $target, array('agenda' => 2030));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $target = $form->getData();

            $this->getDoctrine()->getManagerForClass(Target::class)->persist($target);
            $this->getDoctrine()->getManagerForClass(Target::class)->flush();
            $this->addFlash('success', 'Cible ajoutée avec succès');
            return $this->redirectToRoute('app_target_new');
        }

        return $this->render('goal/target_form.html.twig', [
            'target' => $target,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/target/{id}", name="app_target")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function targetAction($id, Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

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

        $form = $this->createForm(TargetType::class, $target, array('agenda' => 2030));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $target = $form->getData();

            $this->getDoctrine()->getManagerForClass(Target::class)->flush();

            $this->addFlash('success', 'Cible modifiée avec succès');
            return $this->redirectToRoute('app_targets');
        }

        return $this->render('goal/target_form.html.twig', [
            'target' => $target,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/target/{id}/delete", name="app_target_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function deleteTargetAction($id, Request $request)
    {
        try {
            $target = $this->getDoctrine()->getRepository(TArget::class)->find($id);
            $this->getDoctrine()->getManager()->remove($target);
            $this->getDoctrine()->getManager()->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_targets');
        }
        $this->addFlash('success', 'Cible supprimée avec succès');
        return $this->redirectToRoute('app_targets');
    }

    /**
     * @Route("/app/indicators", name="app_indicators")
     */
    public function indicatorsAction()
    {
        $indicators = $indicators = $this->getDoctrine()->getRepository(Indicator::class)->findByAgenda(2030);

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

    /**
     * @Route("/app/indicator/new", name="app_indicator_new")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newIndicatorAction(Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

        $indicator = new Indicator();

        /*$form = $this->createForm(IndicatorType::class, $indicator, [
            'choices' => YearsUtils::choicesYears($startYear),
        ]);*/

        $form = $this->createForm(IndicatorType::class, $indicator, [
            'agenda' => 2030,
            'sessionYear' => $request->getSession()->get('_year'),
            'sessionMinistry' => $request->getSession()->get('_ministry')
        ]);


        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $indicator = $form->getData();

            $desagregations = $form->get('desagregations')->getData();
            $desagregationsarray = array();
            $desagregationsarray[] = 1;
            foreach ($desagregations as $desagregation) {
                $desagregationsarray[] = $desagregation->getId();
            }
            $indicator->setDesagregations($desagregationsarray);

            $this->getDoctrine()->getManagerForClass(Indicator::class)->persist($indicator);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
            $this->addFlash('success', 'Indicateur ajouté avec succès');
            return $this->redirectToRoute('app_indicator_new');
        }

        return $this->render('goal/indicator_form.html.twig', [
            'indicator' => $indicator,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/indicator/{id<\d+>?0}", name="app_indicator")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function indicatorAction($id, Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

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

        if ($indicator->getDesagregations()) {
            $desagregations = array();
            foreach ($indicator->getDesagregations() as $desagragation) {
                $desagregations[] = $this->getDoctrine()->getRepository(Desagregation::class)->findOneBy(['id' => $desagragation]);
            }
            $indicator->setDesagregations($desagregations);
        }

        $form = $this->createForm(IndicatorType::class, $indicator, array('goal'=>$indicator->getTarget()->getGoal(),'communal' => false,
        'sessionYear' => $request->getSession()->get('_year'),
        'sessionMinistry' => $request->getSession()->get('_ministry')));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $indicator = $form->getData();

            $desagregations = $form->get('desagregations')->getData();
            $desagregationsarray = array();
            $desagregationsarray[] = 1;
            foreach ($desagregations as $desagregation) {
                $desagregationsarray[] = $desagregation->getId();
            }
            $indicator->setDesagregations($desagregationsarray);

            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
            $this->addFlash('success', 'Indicateur modifié avec succès');
            return $this->redirectToRoute('app_indicators');
        }

        return $this->render('goal/indicator_form.html.twig', [
            'indicator' => $indicator,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/indicator/{id}/delete", name="app_indicator_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function deleteIndicatorAction($id, Request $request)
    {
        try {
            $indicator = $this->getDoctrine()->getRepository(Indicator::class)->find($id);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->remove($indicator);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_indicators');
        }
        $this->addFlash('success', 'Indicateur supprimé avec succès');
        return $this->redirectToRoute('app_indicators');
    }


    /**
     * @Route("/app/indicators_renseignables", name="app_indicators_renseignables")
     */
    public function indicatorsRenseignablesAction()
    {
        $indicators = $this->getDoctrine()
            ->getRepository(Indicator::class)
            ->findBy(['communal' => true]);

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

    /**
     * @Route("/app/indicator_renseignable/new", name="app_indicator_renseignable_new")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newIndicatorRenseignableAction(Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

        $indicator = new Indicator();

        $form = $this->createForm(IndicatorType::class, $indicator, array('agenda' => 2030,'communal' => true));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $indicator = $form->getData();
            $indicator->setCommunal(true);

            $this->getDoctrine()->getManagerForClass(Indicator::class)->persist($indicator);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
            $this->addFlash('success', 'Indicateur ajouté avec succès');
            return $this->redirectToRoute('app_indicator_renseignable_new');
        }

        return $this->render('goal/indicator_renseignable_form.html.twig', [
            'indicator' => $indicator,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/indicator_renseignable/{id<\d+>?0}", name="app_indicator_renseignable")
     * 
     */
    //@IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function indicatorRenseignableAction($id, Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_goals'));
        }

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

            $form = $this->createForm(IndicatorType::class, $indicator, array('goal'=>$indicator->getTarget()->getGoal(),'communal' => true));
            $form->handleRequest($request);
            
            if ($form->isSubmitted() && $form->isValid()) {
            $indicator = $form->getData();
            $this->getDoctrine()->getManagerForClass(Indicator::class)->persist($indicator);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
            $this->addFlash('success', 'Indicateur modifié avec succès');
            return $this->redirectToRoute('app_indicators_renseignables');
        }
        return $this->render('goal/indicator_renseignable_form.html.twig', [
            'indicator' => $indicator,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/indicator_renseignable/{id}/delete", name="app_indicator_renseignables_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function deleteIndicatorRenseignableAction($id, Request $request)
    {
        try {
            $indicator = $this->getDoctrine()->getRepository(Indicator::class)->find($id);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->remove($indicator);
            $this->getDoctrine()->getManagerForClass(Indicator::class)->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_indicators_renseignables');
        }
        $this->addFlash('success', 'Indicateur supprimé avec succès');
        return $this->redirectToRoute('app_indicators_renseignables');
    }

    /**
     * @Route("/app/desagregations", name="app_desagregations")
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function desagregationsAction()
    {
        $desagregations = $this->getDoctrine()->getRepository(Desagregation::class)->findAll();

        return $this->render('goal/desagregation_list.html.twig', [
            'desagregations' => $desagregations,
        ]);
    }

    /**
     * @Route("/app/desagregation/new", name="app_desagregation_new")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newDesagregationAction(Request $request)
    {

        $desagregation = new Desagregation();

        $form = $this->createForm(DesagregationType::class, $desagregation);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $desagregation = $form->getData();

            $this->getDoctrine()->getManagerForClass(Desagregation::class)->persist($desagregation);

            if ($request->get('modalites')) {
                foreach ($request->get('modalites') as $m) {
                    $modalite = new Modalite();
                    $modalite->setName($m['name']);
                    $modalite->setDesagregation($desagregation);
                    $this->getDoctrine()->getManager()->persist($modalite);
                }
            }

             $this->getDoctrine()->getManager()->flush();

            $this->addFlash('success', 'Désagrégation ajoutée avec succès');
            return $this->redirectToRoute('app_desagregation_new');
        }

        return $this->render('goal/desagregation_form.html.twig', [
            'form' => $form->createView(),
            'desagregation' => $desagregation,
        ]);
    }

    /**
     * @Route("/app/desagregation/{id}", name="app_desagregation")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function desagregationAction($id, Request $request)
    {
        if ($id <=5 ) {
            return $this->redirect($this->generateUrl('app_desagregations'));
        }
        $desagregation = $this->getDoctrine()->getRepository(Desagregation::class)->findOneBy(['id' => $id]);

        $form = $this->createForm(DesagregationType::class, $desagregation);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $desagregation = $form->getData();

            $this->getDoctrine()->getManagerForClass(Desagregation::class)->persist($desagregation);

            $this->getDoctrine()->getRepository(Modalite::class)->deleteAll($desagregation->getId());

            if ($request->get('modalites')) {
                foreach ($request->get('modalites') as $m) {
                    $modalite = new Modalite();
                    $modalite->setName($m['name']);
                    $modalite->setDesagregation($desagregation);
                    $this->getDoctrine()->getManager()->persist($modalite);
                }
            }

             $this->getDoctrine()->getManager()->flush();

            $this->addFlash('success', 'Désagrégation modifiée avec succès');
            return $this->redirectToRoute('app_desagregations');
        }

        return $this->render('goal/desagregation_form.html.twig', [
            'form' => $form->createView(),
            'desagregation' => $desagregation,
        ]);
    }

    /**
     * @Route("/app/desagregation/{id}/delete", name="app_desagregation_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function deleteDesagregationAction($id, Request $request)
    {
        try {
            $desagregation = $this->getDoctrine()->getRepository(Desagregation::class)->find($id);
            $this->getDoctrine()->getManager()->remove($desagregation);
            $this->getDoctrine()->getManager()->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_desagregations');
        }
        $this->addFlash('success', 'Désagrégation supprimée avec succès');
        return $this->redirectToRoute('app_desagregations');
    }


    /**
     * @Route("/app/zones", name="app_zones")
     */
    public function zonesAction()
    {
        // Verify l'acces des communes
        if (($this->isGranted('ROLE_FOCAL') or $this->isGranted('ROLE_DPP')) and  $this->getUser()->getCommune()) {
            return $this->redirect($this->generateUrl('app_login'));
        }
        $zones = $this->getDoctrine()->getRepository(Zone::class)->findAll();

        return $this->render('goal/zone_list.html.twig', [
            'zones' => $zones,
        ]);
    }

    /**
     * @Route("/app/zone/new", name="app_zone_new")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function newZoneAction(Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_zones'));
        }

        $zone = new Zone();

        $form = $this->createForm(ZoneType::class, $zone);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $zone = $form->getData();

            $this->getDoctrine()->getManagerForClass(Zone::class)->persist($zone);
            $this->getDoctrine()->getManagerForClass(Zone::class)->flush();

            $this->addFlash('success', 'Zone ajoutée avec succès');
            return $this->redirectToRoute('app_zone_new');
        }

        return $this->render('goal/zone_form.html.twig', [
            'zone' => $zone,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/zone/{id}", name="app_zone")
     
     */
    //* @IsGranted({"ROLE_ADMIN", "ROLE_MANAGER"})
    public function zoneAction($id, Request $request)
    {
        if ($request->getSession()->get('_application') != 2) {
            return $this->redirect($this->generateUrl('app_zones'));
        }

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

        $form = $this->createForm(ZoneType::class, $zone);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $zone = $form->getData();
            $this->getDoctrine()->getManagerForClass(Zone::class)->flush();
            $this->addFlash('success', 'Zone modifiéz avec succès');
            return $this->redirectToRoute('app_zones');
        }

        return $this->render('goal/zone_form.html.twig', [
            'zone' => $zone,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/app/zone/{id}/delete", name="app_zone_delete")
     * 
     */
    //@IsGranted({"ROLE_ADMIN"})
    public function zoneGoalAction($id, Request $request)
    {
        try {
            $zone = $this->getDoctrine()->getRepository(Zone::class)->find($id);
            $this->getDoctrine()->getManager()->remove($zone);
            $this->getDoctrine()->getManager()->flush();
        } catch (\Exception $e) {
            $this->addFlash('error', 'Une erreur s\'est produite. Veuillez réssayer ou contacter le développeur');
            return $this->redirectToRoute('app_zones');
        }
        $this->addFlash('success', 'Zone supprimés avec succès');
        return $this->redirectToRoute('app_zones');
    }
}
