<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Controller\Admin;

use App\Entity\Adresse;
use App\Entity\Agent;
use App\Entity\AgentAppareil;
use App\Entity\AgentGps;
use App\Entity\AgentQualification;
use App\Entity\AgentRestriction;
use App\Entity\Appareil;
use App\Entity\CategoriePlanification;
use App\Entity\EquipementFamille;
use App\Entity\Groupe;
use App\Entity\Intervention;
use App\Entity\MotifTempsPartiel;
use App\Entity\Post;
use App\Entity\Site;
use App\Entity\TypeEmail;
use App\Entity\TypePlanification;
use App\Entity\TypeTel;
use App\Entity\Utilisateur;
use App\Entity\UtilisateurAdresse;
use App\Entity\UtilisateurAffectation;
use App\Entity\UtilisateurEmail;
use App\Entity\UtilisateurProfil;
use App\Entity\UtilisateurTel;
use App\Form\AgentType;
use App\Form\PostType;
use App\Form\UtilisateurType;
use App\Repository\PostRepository;
use App\Security\PostVoter;
use App\Service\FiltreManager;
use App\Service\LockManager;
use App\Utils\Functions;
use DateTime;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Controller used to manage blog contents in the backend.
 *
 * Please note that the application backend is developed manually for learning
 * purposes. However, in your real Symfony application you should use any of the
 * existing bundles that let you generate ready-to-use backends without effort.
 *
 * See http://knpbundles.com/keyword/admin
 *
 * @Route("/agents")
 * @IsGranted("ROLE_USER")
 *
 */
class AgentController extends ParentAdminController
{
    /**
     * Lists all entities.
     * @Route("/liste_agents", methods="GET", name="list_agents")
     */
    public function listAgents(FiltreManager $filtreManager): Response
    {
        $datas = [
            'columns' => [
                ['dataField' => 'sitesListe', 'caption' => 'Site(s)'],
                //['dataField' => 'id', 'caption' => 'identifiant agent', 'alignment' => 'left' ,'sortOrder' => 'asc'],
                ['dataField' => 'code_agent', 'caption' => 'identifiant agent', 'alignment' => 'left' ,'sortOrder' => 'asc'],
                ['dataField' =>'profil_name', 'caption' => 'Type'],
                ['dataField' => 'nomPrenom', 'caption' => 'Nom'],
                ['dataField' =>'nom_responsable', 'caption' => 'Groupe'],
               // ['dataField' => 'groupe_affectation', 'caption' => 'Groupe', 'alignment' => 'left'],
                ['dataField' => 'planifiable', 'caption' => 'Planifiable'],
                ['dataField' => 'actif', 'dataType' => 'boolean', 'width' => 130, "filterValues" => [true], 'lookup' => ['valueExpr' => 'value', 'displayExpr' => 'text','dataSource' => [['value' => true, 'text' => 'Actif'], ['value'=> false, 'text' => "Inactif"]]]],
                ['dataField' => 'adresse', 'caption' => 'Adresse', 'visible' => false ],
                ['dataField' => 'telephone', 'caption' => 'Téléphone', 'visible' => false],
                ['dataField' => 'qualifications', 'caption' => 'Qualification', 'encodeHtml' => false, 'visible' => false],
                ['dataField' => 'poleLibelle', 'caption' => 'Pôle', 'visible' => false],
            ],
            'column_autowidth' => true,
            'rang_tri' => false,
            'get_path' => $this->generateUrl('get_agents'),
            'filtreDefaut' => $filtreManager->getDefaultFilter($this->getUser(), 'Agent'),
            'filtreDefautUtilisateur' => $filtreManager->getDefaultFilterUtilisateur($this->getUser(), 'Agent'),
        ];

        $actions = [
            ['name' => 'Agent', 'icon' => 'fa-plus', 'class' => 'btn-success', 'id' => 'link-add-' . 'Utilisateur'],
        ];

        $formView = $this->createForm(UtilisateurType::class, null, ['action' => $this->generateUrl('parent_createform', ['page' => 'Utilisateur'])])->createView();


        return $this->render('admin/list.html.twig', [
            'datagrid_style' => 'full',
            'page' => 'Utilisateur',
            'page_filtre' => 'Agent',
            'datas' => $datas,
            'actions' => $actions,
            'form' => $formView,
            'show_path' => $this->generateUrl('show_agent', ['id' => 1]),
        ]);
    }

    /**
     * Lists all entities.
     * @Route("/get/agents", methods="GET", name="get_agents")
     */
    public function getAgents(SerializerInterface $serializer, Request $request) {
        $entities = $this->getDoctrine()->getManager()->getRepository(Utilisateur::class)->getAgents();
        $total = $this->getDoctrine()->getManager()->getRepository(Utilisateur::class)->countAgents();
        $datas = Functions::getSerialisedEntities($entities, $serializer, 'site_list');
        $response = json_encode(['data' => $datas, 'totalCount' => $total]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }

    /**
     * Lists all entities.
     * @Route("/agent/{id}", methods="GET", name="show_agent")
     */
    public function showAgent(Utilisateur $agent, LockManager $lockManager, Request $request): Response
    {
         $qualificationsGrid = [
             'columns' => [
                 ['dataField' =>'libelle',
                     'caption' => 'Qualifications',
                     'dataType' => 'number',
                     'validationRules' => [["type" =>'required']],
                     'sortOrder' => 'asc',
                     'lookup' => [
                         'dataSource'=>  "common.createCustomStore('EquipementFamille')",//, '', '" . $this->generateUrl('get_qualifications_available', ['id' => $agent->getId()]) ."')",
                         'displayExpr'=> "codeLibelle",
                         'valueExpr'=> "code",
                     ]
                 ],
             ],
             'rang_tri' => false,
             'get_path' => $this->generateUrl('get_agent_qualifications', ['id' => $agent->getId()]),
             'create_path' => $this->generateUrl('post_agent_qualification', ['id' => $agent->getId()]),
             'delete_path' => $this->generateUrl('delete_agent_qualification'),
             'key_add' => $agent->getId(),
             'editing' => [ 'mode' => "row", 'allowUpdating' => false,  'allowDeleting' =>  true, 'allowAdding' => true],
             'toolbarInvisible' => true,
         ];

        $categClient = $this->getDoctrine()->getRepository(CategoriePlanification::class)->find(CategoriePlanification::ID_CATEG_CLIENT);
        $typePlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->getIdLibelle($categClient);
        $restrictionsGrid = [
            'columns' => [
                ['dataField' =>'idtype_planification',
                    'caption' => 'Inaptitudes physiques',
                    'dataType' => 'number',
                    'validationRules' => [["type" =>'required']],
                    'sortOrder' => 'asc',
                    'lookup' => [
                        'dataSource'=>  $typePlanification,//, '', '" . $this->generateUrl('get_qualifications_available', ['id' => $agent->getId()]) ."')",
                        'displayExpr'=> "libelle",
                        'valueExpr'=> "id",
                    ]
                ],
                ['dataField' => 'motif', 'caption' => 'Motif'],
                ['dataField' => 'date_debut', 'caption' => 'Date début', 'dataType' => "date", 'format' => 'shortDate', 'width' => '17%'],
                ['dataField' => 'date_fin', 'caption' => 'Date fin', 'dataType' => "date", 'format' => 'shortDate', 'width' => '17%'],
            ],
            'rang_tri' => false,
            'get_path' => $this->generateUrl('get_agent_restrictions', ['id' => $agent->getId()]),
            'patch_path' => $this->generateUrl('patch_agent_restriction', ['id' => $agent->getId()]),
            'create_path' => $this->generateUrl('post_agent_restriction', ['id' => $agent->getId()]),
            'delete_path' => $this->generateUrl('delete_agent_restriction'),
            'key_add' => $agent->getId(),
            'editing' => [ 'mode' => "row", 'allowUpdating' => true,  'allowDeleting' =>  true, 'allowAdding' => true],
            'disableOnlyEditing' => ['idtype_planification'],
            'toolbarInvisible' => true,
        ];

        $appareilGrid = [
            'columns' => [
                ['dataField' => 'appareil', 'caption' => 'Appareil',
                    'width' => '30%',
                    'dataType' => 'number',
                    'sortOrder' => 'asc',
                    'validationRules' => [["type" =>'required']],
                    'lookup' => [
                        'dataSource'=>  "common.createCustomStore('Appareil')",//, '', '" . $this->generateUrl('get_qualifications_available', ['id' => $agent->getId()]) ."')",
                        'displayExpr'=> "libelle_long",
                        'valueExpr'=> "id",
                    ]],
                ['dataField' => 'typeMetrologique', 'caption' => 'Type', 'allowEditing' => false],
                ['dataField' =>'reference', 'caption' => 'N°identification'],
                ['dataField' => 'date_delivrance', 'caption' => 'Date délivrance', 'alignment' => 'left', 'dataType' => "date", 'format' => 'shortDate'],
                ['dataField' => 'date_limite', 'caption' => 'Date limite', 'dataType' => "date", 'format' => 'shortDate'],
                ['dataField' => 'date_restitution', 'caption' => 'Date Restitution', 'dataType' => "date", 'format' => 'shortDate'],
                ['dataField' => 'commentaire', 'caption' => 'Commentaire' ],
                [ 'caption' => "Actions", "type" => 'buttons', 'width' => 110],
            ],
            'column_autowidth' => true,
            'rang_tri' => false,
            'get_path' => $this->generateUrl('get_agent_appareils', ['id' => $agent->getId()]),
            'editing' => [ 'mode' => "row", 'allowUpdating' => true, 'allowDeleting' => false, 'allowAdding' => true],
            'patch_path' => $this->generateUrl('patch_agent_appareil', ['id' => $agent->getId()]),
            'create_path' => $this->generateUrl('post_agent_appareil', ['id' => $agent->getId()]),
            'disableOnlyEditing' => ['date_delivrance','reference','typeMetrologique', 'appareil'],
            'disableOnlyAdding' => ['date_restitution'],
        ];

        $typesProfil = $this->getDoctrine()->getRepository(UtilisateurProfil::class)->findAll();
         $motifs = $this->getDoctrine()->getRepository(MotifTempsPartiel::class)->findAll();
         $utilisateursPlanning = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursPlanning();
         $utilisateurResponsable = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursResponsable();
        $checkLock = $lockManager->checkLock('Agent', $request->get('id') , $this->getUser());
        return $this->render('agent/agent_show.html.twig', [
            'agent' => $agent,
           // 'form' => $formView,
            'page' => 'Agent',
            'qualificationsGrid' => $qualificationsGrid,
            'appareilsGrid' => $appareilGrid,
            'restrictionsGrid' => $restrictionsGrid,
            'typesProfil' => $typesProfil,
            'motifs' => $motifs,
            'lock' => $checkLock,
            'utilisateursPlanning' => $utilisateursPlanning,
            'utilisateursResponsable' => $utilisateurResponsable,
        ]);
    }

    /**
     * getAgent qualifications
     * @Route("/agent/{id}/qualifications", methods="GET", name="get_agent_qualifications")
     */
    public function getQualificationsAgentsGrid(Utilisateur $agent) {
        $result = [];
        foreach ($agent->getAgentQualifications() as $qualification) {
            $equipementFamille = $qualification->getEquipementFamille();
            $result[] = ['id' => $agent->getId() . '-' . $equipementFamille->getId(), 'code' => $equipementFamille->getCode(), 'libelle' => $equipementFamille->getCode() . ' - ' . $equipementFamille->getLibelle()];
        }
        sort($result);
        $response = json_encode(['data' => $result, 'totalCount' => count($result)]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }
    /**
     * getAgent Restrictions
     * @Route("/agent/{id}/restrictions", methods="GET", name="get_agent_restrictions")
     */
    public function getRestrictionsAgentsGrid(Utilisateur $agent) {
        $result = [];
        foreach ($agent->getAgentRestrictions() as $restriction) {
            $typePlanification = $restriction->getTypePlanification();
            $result[] = ['id' => $agent->getId() . '-' . $typePlanification->getId(), 'motif' => $restriction->getMotif() , "idtype_planification" => $typePlanification->getId(),'libelle' => $typePlanification->getLibelle(),
                'date_debut' => ($restriction->getDateDebut()) ? $restriction->getDateDebut()->format('Y-m-d\TH:i:sP') : null,
                'date_fin' => ($restriction->getDateFin()) ? $restriction->getDateFin()->format('Y-m-d\TH:i:sP') : null, ];
        }
        sort($result);
        $response = json_encode(['data' => $result, 'totalCount' => count($result)]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }

    /**
     * getAgent appareils
     * @Route("/agent/{id}/appareils", methods="GET", name="get_agent_appareils")
     */
    public function getAppareilsAgentsGrid(Utilisateur $agent) {
        $result = [];
        foreach ($agent->getAgentAppareils() as $agentAppareil) {
            $appareil = $agentAppareil->getAppareil();
            $result[] = [
                'id' => $appareil->getId(),
                'typeMetrologique' => $appareil->getTypeMetrologique(),
                'appareil' => $appareil->getId() ,
                'reference' => $agentAppareil->getReference(),
                'date_delivrance' => ($agentAppareil->getDateDelivrance()) ?$agentAppareil->getDateDelivrance()->format('Y-m-d\TH:i:sP') : null,
                'date_restitution' => ($agentAppareil->getDateRestitution()) ?$agentAppareil->getDateRestitution()->format('Y-m-d\TH:i:sP') : null,
                'date_limite' => ($agentAppareil->getDateLimiteRenouvellement()) ? $agentAppareil->getDateLimiteRenouvellement()->format('Y-m-d\TH:i:sP') : null,
                'commentaire' => $agentAppareil->getCommentaire(),
            ];
        }
        $response = json_encode(['data' => $result, 'totalCount' => count($result)]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }

    /**
     * create agent  qualification
     * @Route("/agent/{id}/appareil", methods="POST", name="post_agent_appareil")
     *  * @Route("/agent/{id}/appareil/{idappareil}", methods="PATCH", name="patch_agent_appareil")
     */
    public function createAgentAppareil(Utilisateur $agent, $idappareil = null,  Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        foreach($datas as $key => $value) {
            $datas[$key] = Functions::clearData($value);
        }

        if (isset($datas['appareil']) || $idappareil) {
            if (!$idappareil) {
                $appareil = $this->getDoctrine()->getRepository(Appareil::class)->find($datas['appareil']);
                $agentAppareil = null;
            }
            else {
                $appareil = $this->getDoctrine()->getRepository(Appareil::class)->find($idappareil);
                $agentAppareil = $this->getDoctrine()->getRepository(AgentAppareil::class)->findOneBy(['utilisateur_agent' => $agent, 'appareil' => $appareil]);
            }

            if ($appareil) {
                if (!$agentAppareil)$agentAppareil = new AgentAppareil();
                $agentAppareil->setAppareil($appareil);
                $agentAppareil->setUtilisateurAgent($agent);

                if (isset($datas['commentaire'])) $agentAppareil->setCommentaire($datas['commentaire']);
                if (isset($datas['reference'])) $agentAppareil->setReference($datas['reference']);
                if (isset($datas['date_delivrance'])) {
                    $date = Functions::getDateTimeFromString($datas['date_delivrance']);
                    $agentAppareil->setDateDelivrance($date);
                }
                if (isset($datas['date_limite']) && $appareil->getMetrologique()) {
                    $date = Functions::getDateTimeFromString($datas['date_limite']);
                    $agentAppareil->setDateLimiteRenouvellement($date);
                }
                if (isset($datas['date_restitution']) && !empty($datas['date_restitution'])) {
                    $date = Functions::getDateTimeFromString($datas['date_restitution']);
                    $agentAppareil->setDateRestitution($date);
                }

                $em->persist($agentAppareil);
                $em->flush();
            }
        }

        return new JsonResponse(['messages' => ['success' => ["Ajout effectué avec succès"]]], Response::HTTP_OK);
    }

    /**
     * create agent  restriction
     * @Route("/agent/{id}/appareil", methods="POST", name="post_agent_restriction")
     *  * @Route("/agent/{id}/restriction/{idplanification}", methods="PATCH", name="patch_agent_restriction")
     */
    public function createAgentPlanification(Utilisateur $agent, $idplanification = null,  Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        foreach($datas as $key => $value) {
            $datas[$key] = Functions::clearData($value);
        }

        if (isset($datas['idtype_planification']) || $idplanification) {
            if (!$idplanification) {
                $typePlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->find((int)$datas['idtype_planification']);
                $agentRestriction = null;
            }
            else {
                $explodedPlan = explode('-', $idplanification);
                $typePlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->find($explodedPlan[1]);
                $agentRestriction = $this->getDoctrine()->getRepository(AgentRestriction::class)->findOneBy(['utilisateur_agent' => $agent, 'type_planification' => $typePlanification]);
            }

            if ($typePlanification) {
                if (!$agentRestriction)$agentRestriction = new AgentRestriction();
                $agentRestriction->setTypePlanification($typePlanification);
                $agentRestriction->setUtilisateurAgent($agent);

                if (isset($datas['motif'])) $agentRestriction->setMotif($datas['motif']);
                if (isset($datas['date_debut'])) {
                    if (!empty($datas['date_debut'])) {
                        $date = Functions::getDateTimeFromString($datas['date_debut']);
                        $agentRestriction->setDateDebut($date);
                    } else {
                        $agentRestriction->setDateDebut(null);
                    }
                }
                if (isset($datas['date_fin']) ) {
                    if (!empty($datas['date_fin'])) {
                        $date = Functions::getDateTimeFromString($datas['date_fin']);
                        $agentRestriction->setDateFin($date);
                    } else {
                        $agentRestriction->setDateFin(null);
                    }

                }

                $em->persist($agentRestriction);
                $em->flush();
            }
        }

        return new JsonResponse(['messages' => ['success' => ["Ajout effectué avec succès"]]], Response::HTTP_OK);
    }


    /**
     * getAgent qualifications
     * @Route("/agent/{id}/qualifications_available", methods="GET", name="get_qualifications_available")
     */
    public function getQualificationsAvailable(Utilisateur $agent, SerializerInterface $serializer) {
        $result = [];
        $equipementsFamilleAgent = [];
        foreach($agent->getAgentQualifications() as $agentQualification) {
            $equipementsFamilleAgent[] = $agentQualification->getEquipementFamille();
        }
        $equipementsFamilleAvailable = $this->getDoctrine()->getRepository(EquipementFamille::class)->getAvailable($equipementsFamilleAgent);
        $datas = Functions::getSerialisedEntities($equipementsFamilleAvailable, $serializer, 'site_list');
        $response = json_encode(['data' => $datas, 'totalCount' => count($equipementsFamilleAvailable)]);

        return new Response(
            $response,
            Response::HTTP_OK,
            ['Content-type' => 'application/json']
        );
    }

    /**
     * MAJ agent contact
     * @Route("/agent/{id}", methods="POST", name="patch_agent")
     */
    public function updateAgentContact(Utilisateur $agent, Request $request, LockManager $lockManager) {
        $em = $this->getDoctrine()->getManager();
        $modif = false;
        $datas = $request->request->all();

        $telPro = $agent->getTelPro();
        $telPerso = $agent->getTelPerso();
        $emailPerso = $agent->getEmailPerso();

        $messages = [];

        foreach($datas as $key => $value) {
            if (!is_array($value))
                $datas[$key] = Functions::clearData($value);
        }

        if ($datas['tel_pro']) {
            if ($telPro && $datas['tel_pro'] != $telPro->getNumero()) {
                $modif = true;
                $telPro->setNumero($datas['tel_pro']);
            } elseif (!$telPro) {
                $modif = true;
                $telPro = new UtilisateurTel();
                $typeTel = $this->getDoctrine()->getRepository(TypeTel::class)->find(TypeTel::ID_TEL_BUREAU);
                $telPro->setUtilisateur($agent)->setNumero($datas['tel_pro'])->setTypeTel($typeTel);
            }
            $em->persist($telPro);
        }
        if ($datas['tel_perso']) {
            if ($telPerso && $datas['tel_perso'] != $telPerso->getNumero()) {
                $modif = true;
                $telPerso->setNumero($datas['tel_perso']);
            } elseif (!$telPerso) {
                $modif = true;
                $telPerso = new UtilisateurTel();
                $typeTel = $this->getDoctrine()->getRepository(TypeTel::class)->find(TypeTel::ID_TEL_PORTABLE);
                $telPerso->setUtilisateur($agent)->setNumero($datas['tel_perso'])->setTypeTel($typeTel);
            }
            $em->persist($telPerso);
        }
        if ($datas['mail_perso']){
            if ($emailPerso && $datas['mail_perso'] != $emailPerso->getEmail()) {
                $modif = true;
                $emailPerso->setEmail($datas['mail_perso']);
            } elseif (!$emailPerso) {
                $modif = true;
                $emailPerso = new UtilisateurEmail();
                $typeMail = $this->getDoctrine()->getRepository(TypeEmail::class)->find(TypeEmail::ID_EMAIL_PERSO);
                $emailPerso->setUtilisateur($agent)->setEmail($datas['mail_perso'])->setTypeEmail($typeMail);
            }
            $em->persist($emailPerso);
        }
        if (isset($datas['photo_agent']) && !empty($datas['photo_agent'])) {
            $modif = true;
            $agent->setPhoto($datas['photo_agent']);
        }
        if (isset($datas['agi']) && $datas['agi'] != $agent->getCodeClientAgi()){
            $modif = true;
            $agent->setCodeClientAgi($datas['agi']);
            $em->persist($agent);
        }
        if (isset($datas['adresse']) && !empty($datas['adresse'])  && isset($datas['code_postal']) && !empty($datas['code_postal']) && isset($datas['ville']) && !empty($datas['ville'])){
            $utilisateurAdresse = $agent->getAdresseActive();
            $coordinates = explode(',',$datas['coordinates']);
            if (!$utilisateurAdresse) {
                $utilisateurAdresse = new UtilisateurAdresse();
                $utilisateurAdresse->setUtilisateur($agent);
                $utilisateurAdresse->setActif(true);
                $utilisateurAdresse->setDateApplication(new DateTime());
                $adresse = new Adresse();
                $utilisateurAdresse->setAdresse($adresse);
            }
            $utilisateurAdresse->getAdresse()->setAdresse($datas['adresse']);
            $utilisateurAdresse->getAdresse()->setCodePostal($datas['code_postal']);
            $utilisateurAdresse->getAdresse()->setVille($datas['ville']);
            $utilisateurAdresse->getAdresse()->setLatitude($coordinates[1]);
            $utilisateurAdresse->getAdresse()->setAdresseComplement('');
            $utilisateurAdresse->getAdresse()->setLongitude($coordinates[0]);

            $em->persist($utilisateurAdresse);
            $em->flush();
        }
        //on test les datas
        if ($modif) {
            $em->flush();
        }
        if ($datas['process'] == 'close') {
            $lockManager->deleteLock('Agent', $agent->getId() , $this->getUser());
            $script = '<script>window.close();</script>';
            return new Response($script);
        }

        //return new JsonResponse(['messages' => $messages], Response::HTTP_OK);
        $this->addFlash('success', "Modification effectuée avec succès");
        return $this->redirect($this->generateUrl('show_agent', ['id' => $agent->getId()]));
    }

    /**
     * MAJ agent adresse
     * @Route("/agent/{id}/adresse", methods="POST", name="patch_agent_adresse")
     */
    public function updateAgentAdresse(Utilisateur $agent, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        foreach($datas as $key => $value) {
            $datas[$key] = Functions::clearData($value);
        }

        if (isset($datas['adresse']) && isset($datas['code_postal']) && isset($datas['ville'])){
            $utilisateurAdresse = $agent->getAdresseActive();
            $coordinates = explode(',',$datas['coordinates']);
            if (!$utilisateurAdresse) {
                $utilisateurAdresse = new UtilisateurAdresse();
                $utilisateurAdresse->setUtilisateur($agent);
                $utilisateurAdresse->setActif(true);
                $utilisateurAdresse->setDateApplication(new DateTime());
                $adresse = new Adresse();
                $utilisateurAdresse->setAdresse($adresse);
            }
            $utilisateurAdresse->getAdresse()->setAdresse($datas['adresse']);
            $utilisateurAdresse->getAdresse()->setCodePostal($datas['code_postal']);
            $utilisateurAdresse->getAdresse()->setVille($datas['ville']);
            $utilisateurAdresse->getAdresse()->setLatitude($coordinates[1]);
            $utilisateurAdresse->getAdresse()->setLongitude($coordinates[0]);

            $em->persist($utilisateurAdresse);
            $em->flush();
        }


        return new JsonResponse(['messages' => ['success' => ["Modification effectuée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * deleteAgent qualifications
     * @Route("/agent_qualification/{idAgentQualification}", methods="DELETE", name="delete_agent_qualification")
     */
    public function deleteQualificationAgent($idAgentQualification = null) {
        if ($idAgentQualification) {
            $exploded = explode('-', $idAgentQualification);
            $agent = $this->getDoctrine()->getRepository(Utilisateur::class)->find($exploded[0]);
            $equipementFamille = $this->getDoctrine()->getRepository(EquipementFamille::class)->find($exploded[1]);

            $agentQualification = $this->getDoctrine()->getRepository(AgentQualification::class)->findOneBy(['utilisateur_agent' => $agent, 'equipement_famille' => $equipementFamille]);
            $this->getDoctrine()->getManager()->remove($agentQualification);
            $this->getDoctrine()->getManager()->flush();
        }

        return new JsonResponse(['messages' => ['success' => ["Suppression effectuée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * deleteAgent restriction
     * @Route("/agent_restriction/{idAgentRestriction}", methods="DELETE", name="delete_agent_restriction")
     */
    public function deleteRestrictionAgent($idAgentRestriction = null) {
        if ($idAgentRestriction) {
            $exploded = explode('-', $idAgentRestriction);
            $agent = $this->getDoctrine()->getRepository(Utilisateur::class)->find($exploded[0]);
            $typePlanification = $this->getDoctrine()->getRepository(TypePlanification::class)->find($exploded[1]);

            $agentRestriction = $this->getDoctrine()->getRepository(AgentRestriction::class)->findOneBy(['utilisateur_agent' => $agent, 'type_planification' => $typePlanification]);
            $this->getDoctrine()->getManager()->remove($agentRestriction);
            $this->getDoctrine()->getManager()->flush();
        }

        return new JsonResponse(['messages' => ['success' => ["Suppression effectuée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * create agent  qualification
     * @Route("/agent/{id}/qualifications", methods="POST", name="post_agent_qualification")
     */
    public function createAgentQualification(Utilisateur $agent, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        if (isset($datas['libelle'])) {
            $equipementFamille = $this->getDoctrine()->getRepository(EquipementFamille::class)->findOneBy(['code' => $datas['libelle']]);
            if ($equipementFamille) {
                $agentQualification = new AgentQualification();
                $agentQualification->setEquipementFamille($equipementFamille);
                $agentQualification->setUtilisateurAgent($agent);

                $em->persist($agentQualification);
                $em->flush();
            }
        }

        return new JsonResponse(['messages' => ['success' => ["Ajout effectué avec succès"]]], Response::HTTP_OK);
    }


    /**
     * @Route("/agent/{id}/quitter_entreprise", methods="POST", name="agent_quitter_entreprise")
    */
    public function quitterEntreprise(Utilisateur $agent, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();

        if (!empty($datas['date_sortie'])) {
            $date_sortie = DateTime::createFromFormat('Y-m-d', $datas['date_sortie']);
            $now = new DateTime();

            //si date de sortie inférieure on désactive l'agent en plus de mettre une date de fin à son affectation
            $affectation = $agent->getActiveUtilisateurAffectation();
            $affectationNext = $agent->getNextAffectation();
            if ($affectationNext) $em->remove($affectationNext);
            if (!is_null($affectation)) {
                $affectation->setFinEffet($now);
                if ($date_sortie < $now) {
                    $agent->setActif(false);
                    $affectation->setActif(false);

                    $em->persist($agent);
                }
                $em->persist($affectation);
                $em->flush();
            }
        }

        $datas = $this->getDatasProg();
        $datas['agent'] = $affectation->getUtilisateur();
        $datas['affectation'] = $affectation;
        $datas['type_affichage'] = 'edit';

        //return $this->redirect($this->generateUrl('show_agent', ['id' => $agent->getId()]));
        $html = $this->renderView('agent/_boutons_prog_quitter.html.twig', $datas);
        return new JsonResponse(['html' => $html, 'messages' => ['success' => ["Modification effectué avec succès"]]], Response::HTTP_OK);
    }

    /**
     * @Route("/agent/{id}/programmer_changement", methods="POST", name="agent_programmer_changement")
     */
    public function programmerChangement(Utilisateur $agent,  Request $request) {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $new = true;

        $affectation_actuelle = $agent->getActiveUtilisateurAffectation();
        if ($affectation_actuelle) {
            $affectation_actuelle->setFinEffet(null);
            $em->persist($affectation_actuelle);
        }

        $affectation = $agent->getNextAffectation();

        if (!$affectation) $affectation = new UtilisateurAffectation();
        else $new = false;
        $affectation->setUtilisateur($agent);
        $affectation->setActif(false);

        if ($datas['utilisateur_planning']) {
            $utilisateurPlanning = $this->getDoctrine()->getRepository(Utilisateur::class)->find($datas['utilisateur_planning']);
            $affectation->setUtilisateurPlanning($utilisateurPlanning);
        }
        if ($datas['temps_travail']) $affectation->setTempsTravail($datas['temps_travail']);

        if (isset($datas['motif']) && $datas['motif']) {
            $motif = $this->getDoctrine()->getRepository(MotifTempsPartiel::class)->find($datas['motif']);
            $affectation->setMotifTempsPartiel($motif);
        }
        $planifiable = (isset($datas['planifiable']) && $datas['planifiable'] == 'OUI') ? true : false;
        $affectation->setPlanifiable($planifiable);
        if ($datas['utilisateur_responsable']) {
            $responsable = $this->getDoctrine()->getRepository(Utilisateur::class)->find($datas['utilisateur_responsable']);
            $affectation->setUtilisateurReponsable($responsable);
        }
        if ($datas['type_profil']) {
            $profil = $this->getDoctrine()->getRepository(UtilisateurProfil::class)->find($datas['type_profil']);
            $affectation->setUtilisateurProfil($profil);
        }
         if (!empty($datas['date_debut_programme'])) {
             $date_debut = DateTime::createFromFormat('Y-m-d', $datas['date_debut_programme']);
             $affectation->setDebutEffet($date_debut);
         }
         $em->persist($affectation);
        $em->flush();

        if ($new)
            $message = "Affectation ajoutée avec succès";
        else
            $message = "Affectation modifiée avec succès";

        $em->refresh($agent);

        $datas = $this->getDatasProg();
        $datas['agent'] = $agent;
        $datas['affectation'] = $agent->getActiveUtilisateurAffectation();
        $datas['type_affichage'] = 'edit';

        //return $this->redirect($this->generateUrl('show_agent', ['id' => $agent->getId()]));
        $html = $this->renderView('agent/_boutons_prog_quitter.html.twig', $datas);
        return new JsonResponse(['html' => $html, 'messages' => ['success' => [$message]]], Response::HTTP_OK);
    }

    /**
     * @Route("/affectation/{id}", methods="GET", name="agent_cancel_affectation")
     */
    public function cancelAffectation(UtilisateurAffectation $affectation) {
        $em = $this->getDoctrine()->getManager();
        $idAgent = $affectation->getUtilisateur()->getId();

        $em->remove($affectation);
        $em->flush();

        $datas = $this->getDatasProg();
        $datas['agent'] = $affectation->getUtilisateur();
        $datas['affectation'] = $affectation;
        $datas['type_affichage'] = 'edit';

        $html = $this->renderView('agent/_boutons_prog_quitter.html.twig', $datas);

        return new JsonResponse(['html' => $html, 'messages' => ['success' => ["Affectation annulée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * @Route("/affectation/{id}/cancel", methods="GET", name="agent_cancel_depart")
     */
    public function cancelDepartEntreprise(UtilisateurAffectation $affectation) {
        $em = $this->getDoctrine()->getManager();

        $affectation->setFinEffet(null);
        $affectation->setActif(true);
        $em->persist($affectation);
        $em->flush();

        $datas = $this->getDatasProg();
        $datas['agent'] = $affectation->getUtilisateur();
        $datas['affectation'] = $affectation;
        $datas['type_affichage'] = 'edit';

        $html = $this->renderView('agent/_boutons_prog_quitter.html.twig', $datas);

        return new JsonResponse(['html' => $html, 'messages' => ['success' => ["Départ annulé avec succès"]]], Response::HTTP_OK);
    }

    /**
     * @Route("/{id}/delete_photo", methods="GET", name="agent_delete_photo")
     */
    public function deletePhotoAgent(Utilisateur $agent) {
        $em = $this->getDoctrine()->getManager();
        $agent->setPhoto(null);
        $em->persist($agent);
        $em->flush();

       // $this->addFlash('success', "Photo supprimée avec succès");

        return new JsonResponse(['messages' => ['success' => ["Photo supprimée avec succès"]]], Response::HTTP_OK);
        //return $this->redirect($this->generateUrl('show_agent', ['id' => $agent->getId()]));
    }

    private function getDatasProg() {
        $typesProfil = $this->getDoctrine()->getRepository(UtilisateurProfil::class)->findAll();
        $motifs = $this->getDoctrine()->getRepository(MotifTempsPartiel::class)->findAll();
        $utilisateursPlanning = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursPlanning();
        $utilisateurResponsable = $this->getDoctrine()->getRepository(Utilisateur::class)->getUtilisateursResponsable();

        return ['typesProfil' => $typesProfil, 'motifs' => $motifs, 'utilisateursPlanning' => $utilisateursPlanning, 'utilisateursResponsable' => $utilisateurResponsable];
    }

    /**
     * Lists all entities.
     * @Route("/domicile", methods="GET", name="domicile")
     */
    public function getDomicile(SerializerInterface $serializer, Request $request) {
        $entities = $this->getDoctrine()->getManager()->getRepository(Utilisateur::class)->getAgents();
        $datas = Functions::getSerialisedEntities($entities, $serializer, 'map');
        return new JsonResponse($datas);
    }

}
