<?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\Appareil;
use App\Entity\EvenementLieu;
use App\Entity\EvenementLieuTypePlanification;
use App\Entity\EvenementObjet;
use App\Entity\InterventionMotifAbsence;
use App\Entity\Planning;
use App\Entity\TypeAppareil;
use App\Entity\TypePlanification;
use App\Entity\TypePlanificationTypeAppareil;
use App\Service\ClientManager;
use App\Service\EquipementManager;
use App\Service\LockManager;
use App\Service\TarifManager;
use App\Utils\Functions;
use DateTime;
use DateTimeZone;
use Doctrine\ORM\Cache\Lock;
use Proxies\__CG__\App\Entity\CategoriePro;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * @Route("/planning")
 * @IsGranted("ROLE_USER")
 *
 */
class PlanningController extends ParentAdminController
{
    /**
     * Lists all entities.
     * @Route("/patch/type_planification/{id}", methods="PATCH", name="patch_type_planification")
     */
    public function patchTypePlanificationAction($id = null, Request $request, SerializerInterface $serializer): Response
    {
         $em = $this->getDoctrine()->getManager();
         $datas = $request->request->all();
         $metadata = $em->getClassMetadata(TypePlanification::class);

         if ($typePlanification =  $em->getRepository(TypePlanification::class)->find($id)) {
             foreach ($datas as $key => $value) {
                if ($key === 'type_appareil_IDs') {
                    // Récupérer les type appareils existants
                    $existingRelations = $typePlanification->getTypePlanificationTypeAppareils();
                    // Supprimer uniquement les type appareils qui ne sont plus nécessaires
                    foreach ($existingRelations as $relation) {
                        if (!in_array($relation->getTypeAppareil()->getId(), $value)) {
                            $em->remove($relation);
                            $typePlanification->removeTypePlanificationTypeAppareil($relation);
                        }
                    }
                    // Ajouter uniquement les nouveaux appareils
                    if (is_array($value)) {
                        $existingTypeAppareilIds = array_map(function($relation) {
                            return $relation->getTypeAppareil()->getId();
                        }, $existingRelations->toArray());

                        foreach ($value as $typeAppareilId) {
                            if (!in_array($typeAppareilId, $existingTypeAppareilIds)) {
                                $typeAppareil = $em->getRepository(TypeAppareil::class)->find($typeAppareilId);
                                if ($typeAppareil) {
                                    $typePlanificationTypeAppareil = new TypePlanificationTypeAppareil();
                                    $typePlanificationTypeAppareil->setTypeAppareil($typeAppareil);
                                    $typePlanificationTypeAppareil->setTypePlanification($typePlanification);
                                    $em->persist($typePlanificationTypeAppareil);
                                }
                            }
                        }
                    }
                } else{
                    $methodName = 'set' . $this->formatSetter(ucfirst($key));
                    $value = $this->getRealValue($value, $metadata, $key);

                    if (method_exists($typePlanification, $methodName))
                        $typePlanification->$methodName($value);
                }
             }
         }
         $em->persist($typePlanification);
         $em->flush();

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

    /**
     * @Route("/patch/intervention_motif_absence/{id}", methods="PATCH", name="patch_intervention_motif_absence")
     */
    public function patchInterventionMotifAbsenceAction($id = null, Request $request, SerializerInterface $serializer): Response
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $metadata = $em->getClassMetadata(InterventionMotifAbsence::class);

        if ($interventionMotifAbsence =  $em->getRepository(InterventionMotifAbsence::class)->find($id)) {
            foreach ($datas as $key => $value) {
                $methodName = 'set' . $this->formatSetter(ucfirst($key));
                $value = $this->getRealValue($value, $metadata, $key);
                if (method_exists($interventionMotifAbsence, $methodName))
                    $interventionMotifAbsence->$methodName($value);
            }
        }
        $em->persist($interventionMotifAbsence);
        $em->flush();
        return new JsonResponse(['messages' => ['success' => ["Modification effectuée avec succès"]]], Response::HTTP_OK);
    }


    /**
     * @Route("/patch/evenement/objet/{idtype_planification}/{id}", methods={"POST", "PATCH"}, name="patch_evenement_objet")
     */
    public function patchEvenementObjetAction($idtype_planification = null, $id = null, Request $request, SerializerInterface $serializer): Response
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $metadata = $em->getClassMetadata(EvenementObjet::class);
        $typePlanification = $this->getDoctrine()->getManager()->getRepository(TypePlanification::class)->findOneBy(['id' => $idtype_planification]);

        if (!$typePlanification) {
            return new JsonResponse(['error' => 'Type de planification non trouvé'], Response::HTTP_NOT_FOUND);
        }

        $message = "Modification effectuée avec succès";
        if ($id) { //modif
            $evenementObjet = $em->getRepository(EvenementObjet::class)->find($id);
            if (!$evenementObjet) {
                return new JsonResponse(['error' => 'Événement non trouvé'], Response::HTTP_NOT_FOUND);
            }
        } else { //create
            $message = "Création effectuée avec succès";
            $evenementObjet = new EvenementObjet();
            $evenementObjet->setTypePlanification($typePlanification);
        }
        
        foreach ($datas as $key => $value) {
            $methodName = 'set' . $this->formatSetter(ucfirst($key));
            $value = $this->getRealValue($value, $metadata, $key);
            if (method_exists($evenementObjet, $methodName)) {
                $evenementObjet->$methodName($value);
            }
        }
        
        $em->persist($evenementObjet);
        $em->flush();

        return new JsonResponse(['messages' => ['success' => [$message]]], Response::HTTP_OK);
    }


    /**
     * @Route("/patch/evenement/lieu/{idtype_planification}/{id}", methods={"POST", "PATCH"}, name="patch_evenement_lieu")
     */
    public function patchEvenementLieuAction($idtype_planification = null, $id = null, Request $request, SerializerInterface $serializer): Response
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $request->request->all();
        $metadata = $em->getClassMetadata(EvenementLieu::class);
        $typePlanification = $this->getDoctrine()->getManager()->getRepository(TypePlanification::class)->findOneBy(['id' => $idtype_planification]);

        if (!$typePlanification) {
            return new JsonResponse(['error' => 'Type de planification non trouvé'], Response::HTTP_NOT_FOUND);
        }

        $message = "Modification effectuée avec succès";
        if ($id) { //modif
            $evenementLieu = $em->getRepository(EvenementLieu::class)->find($id);
            if (!$evenementLieu) {
                return new JsonResponse(['error' => 'Événement non trouvé'], Response::HTTP_NOT_FOUND);
            }
        } else { //create
            $message = "Création effectuée avec succès";
            $evenementLieu = new EvenementLieu();
        }

        foreach ($datas as $key => $value) {
            $methodName = 'set' . $this->formatSetter(ucfirst($key));
            $value = $this->getRealValue($value, $metadata, $key);
            if (method_exists($evenementLieu, $methodName)) {
                $evenementLieu->$methodName($value);
            }
        }

        $em->persist($evenementLieu);
        if(!$id){
            $evenementLieuTypePlanification = new EvenementLieuTypePlanification();
            $evenementLieuTypePlanification->setTypePlanification($typePlanification);
            $evenementLieuTypePlanification->setEvenementLieu($evenementLieu);
            $em->persist($evenementLieuTypePlanification);
        }
        $em->flush();

        return new JsonResponse(['messages' => ['success' => [$message]]], Response::HTTP_OK);
    }

    /**
     * @Route("/delete/evenement/lieu/{id}", methods="DELETE", name="delete_evenement_lieu")
     */
    public function deleteEvenementLieu($id = null) {
        $em = $this->getDoctrine()->getManager();
        $evenementLieu = $this->getDoctrine()->getRepository(EvenementLieu::class)->find($id);
        if ($evenementLieu) {
            foreach ($evenementLieu->getEvenementLieuTypePlanifications() as $evenementLieuTypePlanification) {
                $em->remove($evenementLieuTypePlanification);
            }
            $em->remove($evenementLieu);
            $em->flush();
        }
        return new JsonResponse(['messages' => ['success' => ["Suppression effectuée avec succès"]]], Response::HTTP_OK);
    }

    /**
     * @Route("/get/evenement/objets/{idtype_planification}", methods="GET", name="get_evenement_objets")
     */
    public function getEvenementObjets($idtype_planification, SerializerInterface $serializer, Request $request) {
        $evenementObjet = $this->getDoctrine()->getManager()->getRepository(EvenementObjet::class)->findBy(['type_planification' => $idtype_planification]);

        $datas = Functions::getSerialisedEntities($evenementObjet, $serializer, 'site_list');
        $response = json_encode(['data' => $datas, 'totalCount' => count($evenementObjet)]);

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

    /**
     * @Route("/get/evenement/lieux/{idtype_planification}", methods="GET", name="get_evenement_lieux")
     */
    public function getEvenementLieux($idtype_planification, SerializerInterface $serializer, Request $request) {
        $evenementLieuTypePlanification = $this->getDoctrine()->getManager()->getRepository(EvenementLieuTypePlanification::class)->findBy(['type_planification' => $idtype_planification]);
        $evenementLieu = $this->getDoctrine()->getManager()->getRepository(EvenementLieu::class)->findBy(['id' => $evenementLieuTypePlanification]);

        $datas = Functions::getSerialisedEntities($evenementLieu, $serializer, 'site_list');
        $response = json_encode(['data' => $datas, 'totalCount' => count($evenementLieu)]);

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