src/Controller/EntrepriseController.php line 523

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CSPE;
  4. use App\Entity\Note;
  5. use App\Entity\User;
  6. use App\Entity\Rappel;
  7. use App\Entity\Contact;
  8. use App\Entity\Contrat;
  9. use App\Entity\GasMeter;
  10. use App\Entity\Entreprise;
  11. use App\Entity\EspaceClient;
  12. use App\Entity\ElectricMeter;
  13. use App\Form\EntrepriseType;
  14. use App\Form\ContratType;
  15. use App\Form\UserEntrepriseType;
  16. use App\Service\PricingService;
  17. use App\Repository\EntrepriseRepository;
  18. use Symfony\Contracts\HttpClient\HttpClientInterface;
  19. use Doctrine\Persistence\ManagerRegistry;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  27. use Psr\Log\LoggerInterface;
  28. class EntrepriseController extends AbstractController
  29. {
  30.     private $pricingService;
  31.     private $logger;
  32.     public function __construct(PricingService $pricingServiceLoggerInterface $logger)
  33.     {
  34.         $this->pricingService $pricingService;
  35.         $this->logger $logger;
  36.     }
  37.     /**
  38.      * @Route("/entreprise", name="app_entreprise")
  39.      */
  40.     public function index(ManagerRegistry $doctrine): Response
  41.     {
  42.         $entreprises $doctrine->getRepository(Entreprise::class)->findAll();
  43.         $array_entreprises = array();
  44.         
  45.         for ($i=0$i count($entreprises); $i++) { 
  46.             // Get all users for this company
  47.             $userIds $entreprises[$i]->getUtilisateur();
  48.             $user_names = [];
  49.             if (!empty($userIds)) {
  50.                 foreach ($userIds as $userId) {
  51.                     $user $doctrine->getRepository(User::class)->find((int)$userId);
  52.                     if ($user) {
  53.                         $user_names[] = $user->getUsername();
  54.                     }
  55.                 }
  56.             }
  57.             $user_name implode(', '$user_names);
  58.             $entreprise_contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
  59.             $entreprise_contacts implode(" "array_map(function($contact) {
  60.                 return $contact->getNom()." ".$contact->getPrenom();
  61.             }, $entreprise_contacts));
  62.             
  63.             // Get electric meters PDLs
  64.             $electric_meters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
  65.             $electric_pdls array_map(function($meter) {
  66.                 return $meter->getPDL();
  67.             }, $electric_meters);
  68.             // Get gas meters PDLs
  69.             $gas_meters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
  70.             $gas_pdls array_map(function($meter) {
  71.                 return $meter->getPDL();
  72.             }, $gas_meters);
  73.             // Combine all PDLs into a searchable string
  74.             $all_pdls implode(' 'array_merge($electric_pdls$gas_pdls));
  75.             $array_entreprises[$i] = [
  76.                 $entreprises[$i]->getRaisonSociale(),
  77.                 $entreprises[$i]->getCommune(),
  78.                 $entreprises[$i]->getSiret(),
  79.                 $entreprise_contacts,
  80.                 $user_name,
  81.                     '<div class="d-flex justify-content-center gap-2">
  82.                         <a href="'.$this->generateUrl('app_entreprise_details',['id' => $entreprises[$i]->getId()]).'" class="btn btn-sm btn-primary"><i class="fa-solid fa-eye"></i></a>
  83.                         <a href="'.$this->generateUrl('app_entreprise_edit',['id' => $entreprises[$i]->getId()]).'" class="btn btn-sm btn-warning"><i class="fa-solid fa-screwdriver-wrench"></i></a>
  84.                         <a href="'.$this->generateUrl('app_entreprise_suppr',['id' => $entreprises[$i]->getId()]).'" class="btn btn-sm btn-danger"><i class="fa-solid fa-trash"></i></a>
  85.                     </div>',
  86.                 $all_pdls// Hidden column containing all PDLs
  87.                 $entreprises[$i]->getNaf(), // Hidden column containing NAF code
  88.             ];
  89.         };
  90.         $contrats $doctrine->getRepository(Contrat::class)->findAll();
  91.         $electricPDLs $doctrine->getRepository(ElectricMeter::class)->createQueryBuilder('e')->select('e.PDL')->getQuery()->getScalarResult();
  92.         $gasPDLs $doctrine->getRepository(GasMeter::class)->createQueryBuilder('g')->select('g.PDL')->getQuery()->getScalarResult();
  93.         // Convertit les résultats en tableau simple de chaînes
  94.         $electricPDLs array_map(fn($item) => $item['PDL'], $electricPDLs);
  95.         $gasPDLs array_map(fn($item) => $item['PDL'], $gasPDLs);
  96.         $array_contrats = [];
  97.         foreach ($contrats as $contrat) {
  98.             $entreprise null;
  99.             $raisonSociale 'entreprise supprimée';
  100.             $editUrl '';
  101.             $deleteUrl '';
  102.             $type ''// 'elec', 'gaz' ou ''
  103.             $pdl $contrat->getPdl();
  104.             $profil '';
  105.             $fournisseur '';
  106.             if ($pdl) {
  107.                 // Essaye de récupérer le compteur élec
  108.                 $electricMeter $doctrine->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $pdl]);
  109.                 if ($electricMeter) {
  110.                     $profil $electricMeter->getProfil() ?? '';
  111.                     $fournisseur $electricMeter->getFournisseur() ?? '';
  112.                 } else {
  113.                     // Sinon, cherche un compteur gaz
  114.                     $gasMeter $doctrine->getRepository(GasMeter::class)->findOneBy(['PDL' => $pdl]);
  115.                     if ($gasMeter) {
  116.                         $profil $gasMeter->getProfil() ?? '';
  117.                         $fournisseur $gasMeter->getFournisseur() ?? '';
  118.                     }
  119.                 }
  120.             }
  121.             try {
  122.                 $entreprise $contrat->getEntreprise();
  123.                 if (!$entreprise) {
  124.                     // entreprise supprimée => on ignore ce contrat
  125.                     continue;
  126.                 }
  127.                 $raisonSociale $entreprise->getRaisonSociale();
  128.                 $actionButtons '
  129.                 <div class="d-flex justify-content-center gap-2">
  130.                     <a href="' $this->generateUrl('app_entreprise_edit_contrat', [
  131.                         'entrepriseId' => $entreprise->getId(),
  132.                         'id' => $contrat->getId()
  133.                     ]) . '" class="btn btn-sm btn-warning" title="Modifier">
  134.                         <i class="fa-solid fa-screwdriver-wrench"></i>
  135.                     </a>
  136.                     <a href="' $this->generateUrl('app_entreprise_delete_contrat', [
  137.                         'entrepriseId' => $entreprise->getId(),
  138.                         'id' => $contrat->getId()
  139.                     ]) . '" class="btn btn-sm btn-danger" title="Supprimer">
  140.                         <i class="fa-solid fa-trash"></i>
  141.                     </a>
  142.                 </div>';
  143.             } catch (\Doctrine\ORM\EntityNotFoundException $e) {
  144.                 continue; // on saute les contrats liés à une entreprise supprimée
  145.             }
  146.             // Statut pastille
  147.             $dateFin $contrat->getDateFin();
  148.             $statut '';
  149.             if (!$dateFin) {
  150.                 $statut '<span class="status-dot status-blue"></span>';
  151.             } else {
  152.                 $today = new \DateTime();
  153.                 $interval $today->diff($dateFin);
  154.                 $daysRemaining = (int)$interval->format('%r%a');
  155.                 $colorClass 'status-gray';
  156.                 if ($daysRemaining 180) {
  157.                     $colorClass 'status-green';
  158.                 } elseif ($daysRemaining 90) {
  159.                     $colorClass 'status-orange';
  160.                 } elseif ($daysRemaining <= 90) {
  161.                     $colorClass 'status-red';
  162.                 }
  163.                 $statut '<span class="status-dot ' $colorClass '"></span>';
  164.             }
  165.             // Détermination du type de contrat via le PDL
  166.             $pdl $contrat->getPdl();
  167.             if ($pdl) {
  168.                 if (in_array($pdl$electricPDLs)) {
  169.                     $type 'elec';
  170.                 } elseif (in_array($pdl$gasPDLs)) {
  171.                     $type 'gaz';
  172.                 }
  173.             }
  174.            $array_contrats[] = [
  175.                 $raisonSociale,                                                             // 0
  176.                 $contrat->getDateDebut() ? $contrat->getDateDebut()->format('d/m/Y') : null// 1
  177.                 $contrat->getDateFin()? $contrat->getDateFin()->format('d/m/Y') : null,     // 2
  178.                 $profil,                                                                    // 3
  179.                 $fournisseur,                                                               // 4
  180.                 $statut,                                                                    // 5
  181.                 $actionButtons,                                                             // 6
  182.                 $type                                                                       // 7 (elec/gaz)
  183.             ];
  184.         }
  185.         // ----------------- PDL – COMPTEURS ÉLECTRIQUES -----------------
  186.         $pdls_elec = [];
  187.         foreach ($doctrine->getRepository(ElectricMeter::class)->findAll() as $meter) {
  188.             $entreprise $doctrine->getRepository(Entreprise::class)
  189.                         ->find($meter->getEntrepriseId());
  190.             // Dernier contrat associé à ce PDL (s’il existe)
  191.             $last $doctrine->getRepository(Contrat::class)
  192.                     ->createQueryBuilder('c')
  193.                     ->where('c.pdl = :pdl')->setParameter('pdl'$meter->getPDL())
  194.                     ->orderBy('c.date_debut''DESC')
  195.                     ->setMaxResults(1)->getQuery()->getOneOrNullResult();
  196.             $lastFin = ($last && $last->getDateFin()) ? $last->getDateFin() : $meter->getDateFin();
  197.             $statut  '';
  198.             if (!$lastFin) {
  199.                 $statut '<span class="status-dot status-blue"></span>';   // aucune date
  200.             } else {
  201.                 $today   = new \DateTime();
  202.                 $dRest   = (int)$today->diff($lastFin)->format('%r%a');     // jours restants
  203.                 $class   'status-gray';
  204.                 if ($dRest 180)      $class 'status-green';
  205.                 elseif ($dRest 90)   $class 'status-orange';
  206.                 else                   $class 'status-red';
  207.                 $statut '<span class="status-dot '.$class.'"></span>';
  208.             }
  209.             $actionButtons =     
  210.             '<div class="d-flex justify-content-center gap-2">
  211.                 <a href="'.$this->generateUrl('app_electric_meter_edit',
  212.                     ['id'=>$meter->getId()]).'" 
  213.                     class="btn btn-sm btn-warning" title="Modifier">
  214.                     <i class="fa-solid fa-screwdriver-wrench"></i>
  215.                 </a>
  216.                 <a href="'.$this->generateUrl('app_electric_meter_suppr',
  217.                     ['id'=>$meter->getId()]).'" 
  218.                     class="btn btn-sm btn-danger" title="Supprimer">
  219.                     <i class="fa-solid fa-trash"></i>
  220.                 </a>
  221.             </div>';
  222.             $pdls_elec[] = [
  223.                 $entreprise $entreprise->getRaisonSociale() : '',
  224.                 $meter->getAdresseCompteur(),
  225.                 $meter->getPDL(),
  226.                 ($last && $last->getDateDebut()) ? $last->getDateDebut()->format('d/m/Y') : '',
  227.                 $lastFin $lastFin->format('d/m/Y') : '',   // ✅ plus d’affectation ici
  228.                 $statut,
  229.                 $meter->getProfil(),
  230.                 $meter->getCAR(),
  231.                 ($last && $last->getFournisseur()) ? $last->getFournisseur() : $meter->getFournisseur(),
  232.                 $meter->getPrix(),
  233.                 $actionButtons,
  234.             ];
  235.         }
  236.             // ------------------ PDL – COMPTEURS GAZ -------------------------
  237.             $pdls_gaz = [];
  238.             foreach ($doctrine->getRepository(GasMeter::class)->findAll() as $meter) {
  239.                 $entreprise $doctrine->getRepository(Entreprise::class)
  240.                             ->find($meter->getEntrepriseId());
  241.                 $last $doctrine->getRepository(Contrat::class)
  242.                         ->createQueryBuilder('c')
  243.                         ->where('c.pdl = :pdl')->setParameter('pdl'$meter->getPDL())
  244.                         ->orderBy('c.date_debut''DESC')
  245.                         ->setMaxResults(1)->getQuery()->getOneOrNullResult();
  246.                 $lastFin = ($last && $last->getDateFin()) ? $last->getDateFin() : $meter->getDateFin();
  247.                 $statut  '';
  248.                 if (!$lastFin) {
  249.                     $statut '<span class="status-dot status-blue"></span>';   // aucune date
  250.                 } else {
  251.                     $today   = new \DateTime();
  252.                     $dRest   = (int)$today->diff($lastFin)->format('%r%a');     // jours restants
  253.                     $class   'status-gray';
  254.                     if ($dRest 180)      $class 'status-green';
  255.                     elseif ($dRest 90)   $class 'status-orange';
  256.                     else                   $class 'status-red';
  257.                     $statut '<span class="status-dot '.$class.'"></span>';
  258.                 }
  259.                 $actionButtons 
  260.                 '<div class="d-flex justify-content-center gap-2">
  261.                     <a href="'.$this->generateUrl('app_gas_meter_edit',
  262.                         ['id'=>$meter->getId()]).'" 
  263.                         class="btn btn-sm btn-warning" title="Modifier">
  264.                         <i class="fa-solid fa-screwdriver-wrench"></i>
  265.                     </a>
  266.                     <a href="'.$this->generateUrl('app_gas_meter_suppr',
  267.                         ['id'=>$meter->getId()]).'" 
  268.                         class="btn btn-sm btn-danger" title="Supprimer">
  269.                         <i class="fa-solid fa-trash"></i>
  270.                     </a>
  271.                 </div>';
  272.                 $pdls_gaz[] = [
  273.                     $entreprise $entreprise->getRaisonSociale() : '',
  274.                     $meter->getAdresseCompteur(),
  275.                     $meter->getPDL(),
  276.                     ($last && $last->getDateDebut()) ? $last->getDateDebut()->format('d/m/Y') : '',
  277.                     $lastFin $lastFin->format('d/m/Y') : '',
  278.                     $statut,
  279.                     $meter->getProfil(),
  280.                     $meter->getCAR(),
  281.                     ($last && $last->getFournisseur()) ? $last->getFournisseur() : $meter->getFournisseur(),
  282.                     $meter->getPrix(),
  283.                     $actionButtons,
  284.                 ];
  285.             }
  286.         // ---- PASSAGE À LA VUE ----
  287.         return $this->render('entreprise/index.html.twig', [
  288.             'entreprises' => $array_entreprises,
  289.             'contrats'    => $array_contrats,
  290.             'pdls_elec'   => $pdls_elec,
  291.             'pdls_gaz'    => $pdls_gaz,
  292.         ]);
  293.     }
  294.     /**
  295.      * @Route("/entreprise/calculate-value", name="app_entreprise_calculate_value", methods={"POST"})
  296.      */
  297.     public function calculateValue(Request $requestManagerRegistry $doctrine): JsonResponse
  298.     {
  299.         $this->logger->debug('Received calculate value request', [
  300.             'car' => $request->request->get('car'),
  301.             'dateDebut' => $request->request->get('dateDebut'),
  302.             'dateFin' => $request->request->get('dateFin'),
  303.             'pdl' => $request->request->get('pdl'),
  304.             'raw_request' => $request->request->all()
  305.         ]);
  306.         // Validate CSRF token
  307.         $submittedToken $request->headers->get('X-CSRF-Token');
  308.         if (!$this->isCsrfTokenValid('calculate-value'$submittedToken)) {
  309.             $this->logger->error('Invalid CSRF token');
  310.             return new JsonResponse(['error' => 'Invalid CSRF token'], 403);
  311.         }
  312.         try {
  313.             $car floatval($request->request->get('car'));
  314.             if ($car <= 0) {
  315.                 throw new \InvalidArgumentException('CAR must be greater than 0');
  316.             }
  317.             // Parse dates and set time to start of day
  318.             $dateDebut = new \DateTime($request->request->get('dateDebut'));
  319.             $dateDebut->setTime(000);
  320.             
  321.             $dateFin = new \DateTime($request->request->get('dateFin'));
  322.             $dateFin->setTime(000);
  323.             if ($dateDebut $dateFin) {
  324.                 throw new \InvalidArgumentException('Start date must be before end date');
  325.             }
  326.             // Check if this is a gas contract by looking up the PDL
  327.             $pdl $request->request->get('pdl');
  328.             $isGasContract false;
  329.             if ($pdl) {
  330.                 $gasMeter $doctrine->getRepository(GasMeter::class)->findOneBy(['PDL' => $pdl]);
  331.                 if ($gasMeter) {
  332.                     $isGasContract true;
  333.                     // For gas contracts, adjust the start date
  334.                     $dateDebut->modify('+1 day');
  335.                 }
  336.             }
  337.             // Create a temporary contract object to calculate the value
  338.             $contrat = new Contrat();
  339.             $contrat->setCar($car);
  340.             $contrat->setDateDebut($dateDebut);
  341.             $contrat->setDateFin($dateFin);
  342.             if ($pdl) {
  343.                 $contrat->setPdl($pdl);
  344.             }
  345.             // Calculate the annual value using the pricing service
  346.             $value $this->pricingService->calculateAnnualValue($contrat);
  347.             $this->logger->debug('Calculated contract value', [
  348.                 'car' => $car,
  349.                 'dateDebut' => $dateDebut->format('d/m/Y'),
  350.                 'dateFin' => $dateFin->format('d/m/Y'),
  351.                 'isGasContract' => $isGasContract,
  352.                 'value' => $value
  353.             ]);
  354.             return new JsonResponse([
  355.                 'value' => $value,
  356.                 'debug' => [
  357.                     'car' => $car,
  358.                     'dateDebut' => $dateDebut->format('d/m/Y'),
  359.                     'dateFin' => $dateFin->format('d/m/Y'),
  360.                     'isGasContract' => $isGasContract
  361.                 ]
  362.             ]);
  363.         } catch (\Exception $e) {
  364.             $this->logger->error('Error calculating contract value', [
  365.                 'error' => $e->getMessage(),
  366.                 'trace' => $e->getTraceAsString()
  367.             ]);
  368.             return new JsonResponse(['error' => 'Error calculating value: ' $e->getMessage()], 500);
  369.         }
  370.     }
  371.     /**
  372.      * @Route("/entreprise/add", name="app_entreprise_add")
  373.      */
  374.     public function add(Request $requestEntityManagerInterface $entityManager): Response
  375.     {
  376.         $entreprises = new Entreprise();
  377.         // using createQueryBuilder
  378.         $utilisateurs $entityManager->createQueryBuilder()
  379.             ->select('u')
  380.             ->from(User::class, 'u')
  381.             ->where('u.roles LIKE :roles')
  382.             ->setParameter('roles''%ROLE_TEAM%')
  383.             ->getQuery()
  384.             ->getResult();
  385.         $array_utilisateurs = array();
  386.         for ($i=0$i count($utilisateurs); $i++) { 
  387.             $array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
  388.         }
  389.         $form $this->createForm(EntrepriseType::class, $entreprises, ['utilisateurs' => $array_utilisateurs]);
  390.         $form->handleRequest($request);
  391.         if ($form->isSubmitted() && $form->isValid()) {
  392.             $entityManager->persist($entreprises);
  393.             $entityManager->flush();
  394.             return $this->redirectToRoute('app_entreprise');
  395.         }
  396.         return $this->render('entreprise/add.html.twig', [
  397.             'entrepriseForm' => $form->createView(),
  398.             'array_utilisateurs' => $array_utilisateurs,
  399.         ]);
  400.     }
  401.     /**
  402.      * @Route("/entreprise/edit/{id}", name="app_entreprise_edit")
  403.      */
  404.     public function edit(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  405.     {
  406.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  407.         $utilisateurs $entityManager->createQueryBuilder()
  408.             ->select('u')
  409.             ->from(User::class, 'u')
  410.             ->where('u.roles LIKE :roles')
  411.             ->setParameter('roles''%ROLE_TEAM%')
  412.             ->getQuery()
  413.             ->getResult();
  414.         $array_utilisateurs = array();
  415.         for ($i=0$i count($utilisateurs); $i++) { 
  416.             $array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
  417.         }
  418.         $form $this->createForm(EntrepriseType::class, $entreprise, ['utilisateurs' => $array_utilisateurs]);
  419.         $form->handleRequest($request);
  420.         $entreprise_entity = [ 'raison_sociale' => $entreprise->getRaisonSociale(),
  421.             'siret' => $entreprise->getSiret(),
  422.             'naf' => $entreprise->getNaf(),
  423.             'rcs' => $entreprise->getRcs(),
  424.             'num_voie' => $entreprise->getNumVoie(),
  425.             'adresse' => $entreprise->getAdresse(),
  426.             'code_postal' => $entreprise->getCodePostal(),
  427.             'commune' => $entreprise->getCommune(),
  428.             'code_insee' => $entreprise->getCodeInsee(),
  429.             'statut' => $entreprise->getStatut(),
  430.             'utilisateur' => $entreprise->getUtilisateur(),
  431.         ];
  432.         if ($form->isSubmitted() && $form->isValid()) {
  433.             $entreprisesEdit $form->getData();
  434.             if($entreprisesEdit->getRaisonSociale() != null){
  435.                 $entreprise->setRaisonSociale($entreprisesEdit->getRaisonSociale());
  436.             }
  437.             if($entreprisesEdit->getSiret() != null){
  438.                 $entreprise->setSiret($entreprisesEdit->getSiret());
  439.             }
  440.             if($entreprisesEdit->getNaf() != null){
  441.                 $entreprise->setNaf($entreprisesEdit->getNaf());
  442.             }
  443.             if($entreprisesEdit->getRcs() != null){
  444.                 $entreprise->setRcs($entreprisesEdit->getRcs());
  445.             }
  446.             if($entreprisesEdit->getNumVoie() != null){
  447.                 $entreprise->setNumVoie($entreprisesEdit->getNumVoie());
  448.             }
  449.             if($entreprisesEdit->getAdresse() != null){
  450.                 $entreprise->setAdresse($entreprisesEdit->getAdresse());
  451.             }
  452.             if($entreprisesEdit->getCodePostal() != null){
  453.                 $entreprise->setCodePostal($entreprisesEdit->getCodePostal());
  454.             }
  455.             if($entreprisesEdit->getCommune() != null){
  456.                 $entreprise->setCommune($entreprisesEdit->getCommune());
  457.             }
  458.             if($entreprisesEdit->getCodeInsee() != null){
  459.                 $entreprise->setCodeInsee($entreprisesEdit->getCodeInsee());
  460.             }
  461.             if($entreprisesEdit->getStatut() != null){
  462.                 $entreprise->setStatut($entreprisesEdit->getStatut());
  463.             }
  464.             if($entreprisesEdit->getUtilisateur() != null){
  465.                 $entreprise->setUtilisateur(array_map('strval'$entreprisesEdit->getUtilisateur()));
  466.             }
  467.             $entityManager->persist($entreprise);
  468.             $entityManager->flush();
  469.             return $this->redirectToRoute('app_entreprise');
  470.         }
  471.         return $this->render('entreprise/edit.html.twig', [
  472.             'entrepriseForm' => $form->createView(),
  473.             'entreprise' => $entreprise_entity
  474.         ]);
  475.     }
  476.     /**
  477.      * @Route("/entreprise/suppr/{id}", name="app_entreprise_suppr")
  478.      */
  479.     public function suppr(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  480.     {
  481.         $notes $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id]);
  482.         for ($i=0$i count($notes); $i++) { 
  483.             $entityManager->remove($notes[$i]);
  484.             $entityManager->flush();
  485.         };
  486.         $rappels $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
  487.         for ($i=0$i count($rappels); $i++) { 
  488.             $entityManager->remove($rappels[$i]);
  489.             $entityManager->flush();
  490.         };
  491.         $electric_meters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  492.         for ($i=0$i count($electric_meters); $i++) { 
  493.             $entityManager->remove($electric_meters[$i]);
  494.             $entityManager->flush();
  495.         };
  496.         $gas_meters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  497.         for ($i=0$i count($gas_meters); $i++) { 
  498.             $entityManager->remove($gas_meters[$i]);
  499.             $entityManager->flush();
  500.         };
  501.         $cspes $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
  502.         for ($i=0$i count($cspes); $i++) { 
  503.             $entityManager->remove($cspes[$i]);
  504.             $entityManager->flush();
  505.         };
  506.         $espace_clients $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
  507.         for ($i=0$i count($espace_clients); $i++) { 
  508.             $entityManager->remove($espace_clients[$i]);
  509.             $entityManager->flush();
  510.         };
  511.         $contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
  512.         for ($i=0$i count($contacts); $i++) { 
  513.             $entityManager->remove($contacts[$i]);
  514.             $entityManager->flush();
  515.         };
  516.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  517.         $entityManager->remove($entreprise);
  518.         $entityManager->flush();
  519.         return $this->redirectToRoute('app_entreprise');
  520.     }
  521.     /**
  522.      * @Route("/entreprise/details/{id}", name="app_entreprise_details")
  523.      */
  524.     public function details(int $idManagerRegistry $doctrine): Response
  525.     {
  526.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  527.         if(!$entreprise){
  528.             return $this->redirectToRoute('app_requetes');
  529.         }
  530.         
  531.         // Get all users for this company
  532.         $userIds $entreprise->getUtilisateur();
  533.         $user_names = [];
  534.         if (!empty($userIds)) {
  535.             foreach ($userIds as $userId) {
  536.                 $user $doctrine->getRepository(User::class)->find((int)$userId);
  537.                 if ($user) {
  538.                     $user_names[] = $user->getUsername();
  539.                 }
  540.             }
  541.         }
  542.         $user_name implode(', '$user_names);
  543.         $entreprise_entity = [ 'id' => $entreprise->getId(),
  544.             'raison_sociale' => $entreprise->getRaisonSociale(),
  545.             'siret' => $entreprise->getSiret(),
  546.             'naf' => $entreprise->getNaf(),
  547.             'rcs' => $entreprise->getRcs(),
  548.             'num_voie' => $entreprise->getNumVoie(),
  549.             'adresse' => $entreprise->getAdresse(),
  550.             'code_postal' => $entreprise->getCodePostal(),
  551.             'commune' => $entreprise->getCommune(),
  552.             'code_insee' => $entreprise->getCodeInsee(),
  553.             'statut' => $entreprise->getStatut(),
  554.             'utilisateur' => $user_names,
  555.         ];
  556.         // Fetch and prepare notes data
  557.         $notes $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id], ['date_creation' => 'DESC']);
  558.         $array_notes = array();
  559.         foreach ($notes as $note) {
  560.             $user $note->getUser();
  561.             $array_notes[] = [
  562.                 'date_creation' => $note->getDateCreation() ? $note->getDateCreation()->format('d/m/Y') : '',
  563.                 'texte' => $note->getTexte(),
  564.                 'user' => $user $user->getUsername() : 'Non défini',
  565.                 'edit_url' => $this->generateUrl('app_note_edit', ['id' => $note->getId()]),
  566.                 'delete_url' => $this->generateUrl('app_note_suppr', ['id' => $note->getId()]),
  567.             ];
  568.         }
  569.         // Fetch and prepare rappels data
  570.         $rappels $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
  571.         $array_rappels = array();
  572.         foreach ($rappels as $rappel) {
  573.             $array_rappels[] = [
  574.                 $rappel->getTitre(),
  575.                 $rappel->getDescription(),
  576.                 $rappel->getEcheance()->format('d/m/Y'),
  577.                 $rappel->isCompleter(),
  578.                 '<a href="'.$this->generateUrl('app_rappel_edit',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-primary mb-1">Modifier</a>
  579.                 <a href="'.$this->generateUrl('app_rappel_suppr',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  580.             ];
  581.     }
  582.         // Fetch electric meters and their PDLs
  583.         $electric_meters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  584.         $array_electric_meters array_map(function($meter) {
  585.             return [
  586.                 'pdl' => $meter->getPDL(),
  587.                 'id' => $meter->getId(),
  588.             ];
  589.         }, $electric_meters);
  590.         $electric_pdls array_map(function($meter) {
  591.             return $meter->getPDL();
  592.         }, $electric_meters);
  593.         // Fetch gas meters and their PDLs
  594.         $gas_meters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  595.         $array_gas_meters array_map(function($meter) {
  596.             return [
  597.                 'pdl' => $meter->getPDL(),
  598.                 'id' => $meter->getId(),
  599.             ];
  600.         }, $gas_meters);
  601.         $gas_pdls array_map(function($meter) {
  602.             return $meter->getPDL();
  603.         }, $gas_meters);
  604.         $cspes $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
  605.         $array_cspes = array();
  606.         for ($i=0$i count($cspes); $i++) { 
  607.             $array_cspes[$i] = [
  608.                 $cspes[$i]->getNotes(),
  609.                 date_format($cspes[$i]->getDate(),'d/m/Y'),
  610.                 $cspes[$i]->getValeur(),
  611.                 '<a href="'.$this->generateUrl('app_cspe_edit',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  612.                 <a href="'.$this->generateUrl('app_cspe_suppr',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  613.             ];
  614.         };
  615.         $espace_clients $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
  616.         $array_espace_clients = array();
  617.         for ($i=0$i count($espace_clients); $i++) {
  618.             $lien $espace_clients[$i]->getLien();
  619.             // Add http:// if no protocol specified
  620.             if (!preg_match("~^(?:f|ht)tps?://~i"$lien)) {
  621.                 $lien "http://" $lien;
  622.             }
  623.             
  624.             // Extract domain name for button text
  625.             $domain parse_url($lienPHP_URL_HOST) ?: $lien;
  626.             $domainParts explode('.'$domain);
  627.             $buttonText count($domainParts) > $domainParts[1] : $domain;
  628.             
  629.             $array_espace_clients[$i] = [
  630.                 $espace_clients[$i]->getFournisseur(),
  631.                 $espace_clients[$i]->getLogin(),
  632.                 $espace_clients[$i]->getMdp(),
  633.                 '<a href="'.$lien.'" target="_blank" type="button" class="btn btn-primary">'.$buttonText.'</a>',
  634.                 '<a href="'.$this->generateUrl('app_espace_client_edit',['id' => $espace_clients[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  635.                 <a href="'.$this->generateUrl('app_espace_client_suppr',['id' => $espace_clients[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  636.             ];
  637.         };
  638.         $contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
  639.         $array_contacts = array();
  640.         for ($i=0$i count($contacts); $i++) { 
  641.             $array_contacts[$i] = [
  642.                 $contacts[$i]->getNom(),
  643.                 $contacts[$i]->getPrenom(),
  644.                 $contacts[$i]->getCivilite(),
  645.                 $contacts[$i]->getFonction(),
  646.                 $contacts[$i]->getFixe(),
  647.                 $contacts[$i]->getEmail(),
  648.                 $contacts[$i]->getPortable(),
  649.                 '<a href="'.$this->generateUrl('app_contact_edit',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  650.                 <a href="'.$this->generateUrl('app_contact_suppr',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  651.             ];
  652.         };
  653.         $contrats $doctrine->getRepository(Contrat::class)->findBy(['entreprise' => $entreprise]);
  654.         $array_contrats = array();
  655.         foreach ($contrats as $contrat) {
  656.             $array_contrats[] = [
  657.                 "id" => $contrat->getId(),
  658.                 "duree" => $contrat->getDuree(),
  659.                 "valeur" => $contrat->getValeur(),
  660.                 "pdl" => $contrat->getPdl(),
  661.                 "car" => $contrat->getCar(),
  662.                 "prix_moyen" => $contrat->getPrixMoyen(),
  663.                 "fournisseur" => $contrat->getFournisseur(),
  664.                 "date_debut" => $contrat->getDateDebut() ? $contrat->getDateDebut()->format('d/m/Y') : '',
  665.                 "date_fin" => $contrat->getDateFin() ? $contrat->getDateFin()->format('d/m/Y') : '',
  666.                 "date_signature" => $contrat->getDateSignature() ? $contrat->getDateSignature()->format('d/m/Y') : '',
  667.                 '<a href="'.$this->generateUrl('app_entreprise_edit_contrat', ['entrepriseId' => $entreprise->getId(), 'id' => $contrat->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  668.                 <a href="'.$this->generateUrl('app_entreprise_delete_contrat', ['entrepriseId' => $entreprise->getId(), 'id' => $contrat->getId()]).'" type="button" class="btn btn-sm btn-danger">Supprimer</a>',
  669.             ];
  670.         }
  671.         return $this->render('entreprise/details.html.twig', [
  672.             'entreprise' => $entreprise_entity,
  673.             'notes' => $array_notes,
  674.             'rappels' => $array_rappels,
  675.             'electric_meters' => $array_electric_meters,
  676.             'gas_meters' => $array_gas_meters,
  677.             'electric_pdls' => $electric_pdls,
  678.             'gas_pdls' => $gas_pdls,
  679.             'cspes' => $array_cspes,
  680.             'espace_clients' => $array_espace_clients,
  681.             'contacts' => $array_contacts,
  682.             'contrats' => $array_contrats,
  683.         ]);
  684.     }
  685.     /**
  686.      * @Route("/entreprise/electric_meter/details/{id}", name="app_electric_meter_details")
  687.      */
  688.     public function electricMeterDetails(Request $requestint $idManagerRegistry $doctrine): JsonResponse
  689.     {
  690.         $pdl $request->query->get('pdl');
  691.         
  692.         if (!$pdl) {
  693.             return new JsonResponse(['error' => 'PDL parameter is required'], 400);
  694.         }
  695.         // First verify the entreprise exists
  696.         $entreprise $doctrine->getRepository(Entreprise::class)->find($id);
  697.         if (!$entreprise) {
  698.             return new JsonResponse(['error' => 'Entreprise not found'], 404);
  699.         }
  700.         // Find the electric meter using standard findOneBy method
  701.         $electricMeter $doctrine->getRepository(ElectricMeter::class)->findOneBy([
  702.             'entreprise_id' => $id,
  703.             'PDL' => $pdl
  704.         ]);
  705.         if (!$electricMeter) {
  706.             return new JsonResponse(['error' => 'Electric meter not found'], 404);
  707.         }
  708.         $meterDetails = [
  709.             'adresseCompteur' => $electricMeter->getAdresseCompteur(),
  710.             'PDL' => $electricMeter->getPDL(),
  711.             'dateDebut' => $electricMeter->getDateDebut() ? $electricMeter->getDateDebut()->format('d/m/Y') : '',
  712.             'dateFin' => $electricMeter->getDateFin() ? $electricMeter->getDateFin()->format('d/m/Y') : '',
  713.             'PS' => $electricMeter->getPS(),
  714.             'profil' => $electricMeter->getProfil(),
  715.             'CAR' => $electricMeter->getCAR(),
  716.             'fournisseur' => $electricMeter->getFournisseur(),
  717.             'prix' => $electricMeter->getPrix()
  718.         ];
  719.         return new JsonResponse($meterDetails);
  720.     }
  721.     /**
  722.      * @Route("/entreprise/{id}/gas-meter-details", name="app_gas_meter_details")
  723.      */
  724.     public function gasMeterDetails(Request $requestint $idManagerRegistry $doctrine): JsonResponse
  725.     {
  726.         $pdl $request->query->get('pdl');
  727.         
  728.         if (!$pdl) {
  729.             return new JsonResponse(['error' => 'PDL parameter is required'], 400);
  730.         }
  731.         // First verify the entreprise exists
  732.         $entreprise $doctrine->getRepository(Entreprise::class)->find($id);
  733.         if (!$entreprise) {
  734.             return new JsonResponse(['error' => 'Entreprise not found'], 404);
  735.         }
  736.         // Find the gas meter using standard findOneBy method
  737.         $gasMeter $doctrine->getRepository(GasMeter::class)->findOneBy([
  738.             'entreprise_id' => $id,
  739.             'PDL' => $pdl
  740.         ]);
  741.         if (!$gasMeter) {
  742.             return new JsonResponse(['error' => 'Gas meter not found'], 404);
  743.         }
  744.         $meterDetails = [
  745.             'adresseCompteur' => $gasMeter->getAdresseCompteur(),
  746.             'PDL' => $gasMeter->getPDL(),  // Added PDL field
  747.             'dateDebut' => $gasMeter->getDateDebut() ? $gasMeter->getDateDebut()->format('d/m/Y') : '',
  748.             'dateFin' => $gasMeter->getDateFin() ? $gasMeter->getDateFin()->format('d/m/Y') : '',
  749.             'profil' => $gasMeter->getProfil(),
  750.             'CAR' => $gasMeter->getCAR(),
  751.             'fournisseur' => $gasMeter->getFournisseur(),
  752.             'prix' => $gasMeter->getPrix(),
  753.         ];
  754.         return new JsonResponse($meterDetails);
  755.     }
  756.     /**
  757.      * @Route("/entreprise/infoclient", name="app_entreprise_infoclient")
  758.      */
  759.     public function infoclient(HttpClientInterface $httpClient): JsonResponse
  760.     {
  761.         // Utilisez les paramètres appropriés pour votre requête
  762.         $url 'https://api.societe.com/api/v1/infoclient';
  763.         $headers = [
  764.             'headers' => [
  765.                 'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
  766.             ],
  767.         ];
  768.         // Effectuez la requête
  769.         $response $httpClient->request('GET'$url$headers);
  770.         // Renvoie la réponse JSON
  771.         return new JsonResponse($response->toArray());
  772.     }
  773.     /**
  774.      * @Route("/entreprise/info_entreprise/{numero}", name="app_entreprise_info_entreprise")
  775.      */
  776.     public function info_entreprise(HttpClientInterface $httpClientManagerRegistry $doctrine$numero): JsonResponse
  777.     {
  778.         // Vérification que l'entreprise n'est pas déjà enregistré en BDD
  779.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['Siret' => $numero]);
  780.         if($entreprise !=null){
  781.             return new JsonResponse("existant");
  782.         }
  783.         $url 'https://api.societe.com/api/v1/entreprise/'.$numero.'/infoslegales';
  784.         $headers = [
  785.             'headers' => [
  786.                 'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
  787.             ],
  788.         ];
  789.         // Effectuez la requête
  790.         $response $httpClient->request('GET'$url$headers);
  791.         // Renvoie la réponse JSON
  792.         return new JsonResponse($response->toArray());
  793.     }
  794.     /**
  795.      * @Route("/entreprise/{id}/new-contrat", name="app_entreprise_new_contrat")
  796.      */
  797.     public function newContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $id): Response
  798.     {
  799.         $entreprise $doctrine->getRepository(Entreprise::class)->find($id);
  800.         
  801.         if (!$entreprise) {
  802.             throw $this->createNotFoundException('Entreprise not found');
  803.         }
  804.         $contrat = new Contrat();
  805.         $contrat->setEntreprise($entreprise);
  806.         $meterId $request->query->get('meterId');
  807.         $meterType $request->query->get('meterType');
  808.         if ($meterId && $meterType) {
  809.             $meter null;
  810.             if ($meterType === 'electric') {
  811.                 $meter $doctrine->getRepository(ElectricMeter::class)->find($meterId);
  812.             } elseif ($meterType === 'gas') {
  813.                 $meter $doctrine->getRepository(GasMeter::class)->find($meterId);
  814.             }
  815.             if ($meter) {
  816.                 $contrat->setPdl($meter->getPDL());
  817.                 $contrat->setCar($meter->getCAR());
  818.                 $contrat->setPrixMoyen($meter->getPrix());
  819.                 $contrat->setFournisseur($meter->getFournisseur());
  820.                 // For both types, set the dates
  821.                 $contrat->setDateDebut($meter->getDateDebut());
  822.                 $contrat->setDateFin($meter->getDateFin());
  823.                 // Calculate initial duration and value
  824.                 if ($meter->getDateDebut() && $meter->getDateFin()) {
  825.                     $dateDebut $meter->getDateDebut();
  826.                     if ($dateDebut) {
  827.                         if ($meterType === 'gas') {
  828.                             $dateDebut->modify('+1 day');
  829.                         }
  830.                     }
  831.                     $duration $this->calculateDurationInMonths($dateDebut$meter->getDateFin());
  832.                     $contrat->setDuree($duration);
  833.                     $annualValue $this->pricingService->calculateAnnualValue($contrat);
  834.                     $contrat->setValeur($annualValue);
  835.                 }
  836.             }
  837.         }
  838.         $pdlChoices $this->getPDLChoicesForEntreprise($doctrine$entreprise);
  839.         $form $this->createForm(ContratType::class, $contrat, [
  840.             'pdl_choices' => $pdlChoices
  841.         ]);
  842.         $form->handleRequest($request);
  843.         if ($form->isSubmitted() && $form->isValid()) {
  844.             // Calculate duration in months
  845.             $duration $this->calculateDurationInMonths($contrat->getDateDebut(), $contrat->getDateFin());
  846.             $contrat->setDuree($duration);
  847.             // Only calculate value if not manually set
  848.             $submittedValue $form->get('valeur')->getData();
  849.             if ($submittedValue === null || $submittedValue === 0.0) {
  850.                 $annualValue $this->pricingService->calculateAnnualValue($contrat);
  851.                 $contrat->setValeur($annualValue);
  852.             }
  853.             // Get the first user as the collaborateur (maintain backward compatibility)
  854.             $userIds $entreprise->getUtilisateur();
  855.             if (!empty($userIds)) {
  856.                 $user $doctrine->getRepository(User::class)->find((int)$userIds[0]);
  857.                 if ($user) {
  858.                     $contrat->setCollaborateur($user);
  859.                 }
  860.             }
  861.             $entityManager->persist($contrat);
  862.             $entityManager->flush();
  863.             if ($request->isXmlHttpRequest()) {
  864.                 return new JsonResponse([
  865.                     'success' => true,
  866.                     'contractId' => $contrat->getId(),
  867.                     'message' => 'Le contrat a été créé avec succès.'
  868.                 ]);
  869.             }
  870.             return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  871.         }
  872.         return $this->render('entreprise/new_contrat.html.twig', [
  873.             'entreprise' => $entreprise,
  874.             'form' => $form->createView(),
  875.         ]);
  876.     }
  877.     /**
  878.      * @Route("/entreprise/{entrepriseId}/edit-contrat/{id}", name="app_entreprise_edit_contrat")
  879.      */
  880.     public function editContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $entrepriseIdint $id): Response
  881.     {
  882.         $entreprise $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
  883.         $contrat $doctrine->getRepository(Contrat::class)->find($id);
  884.         if (!$entreprise) {
  885.             throw $this->createNotFoundException('Entreprise not found');
  886.         }
  887.         if (!$contrat) {
  888.             throw $this->createNotFoundException('Contrat not found');
  889.         }
  890.         // Determine if this is a gas contract
  891.         $isGasContract false;
  892.         $gasMeter $doctrine->getRepository(GasMeter::class)->findOneBy([
  893.             'entreprise_id' => $entrepriseId,
  894.             'PDL' => $contrat->getPdl()
  895.         ]);
  896.         if ($gasMeter) {
  897.             $isGasContract true;
  898.         }
  899.         // S'assurer que l'entreprise est définie sur le contrat
  900.         $contrat->setEntreprise($entreprise);
  901.         $pdlChoices $this->getPDLChoicesForEntreprise($doctrine$entreprise);
  902.         $form $this->createForm(ContratType::class, $contrat, [
  903.             'pdl_choices' => $pdlChoices
  904.         ]);
  905.         $form->handleRequest($request);
  906.         if ($form->isSubmitted() && $form->isValid()) {
  907.             // S'assurer que l'entreprise est toujours définie après la soumission du formulaire
  908.             $contrat->setEntreprise($entreprise);
  909.             // For gas contracts, ensure the start date is adjusted
  910.             $dateDebut $contrat->getDateDebut();
  911.             if ($dateDebut) {
  912.                 if ($isGasContract) {
  913.                     $dateDebut->modify('+1 day');
  914.                 }
  915.             }
  916.             // Recalculate duration in months
  917.             $duration $this->calculateDurationInMonths($dateDebut$contrat->getDateFin());
  918.             $contrat->setDuree($duration);
  919.             // Only calculate value if not manually set
  920.             $submittedValue $form->get('valeur')->getData();
  921.             if ($submittedValue === null || $submittedValue === 0.0) {
  922.                 $annualValue $this->pricingService->calculateAnnualValue($contrat);
  923.                 $contrat->setValeur($annualValue);
  924.             }
  925.             $entityManager->flush();
  926.             return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  927.         }
  928.         return $this->render('entreprise/edit_contrat.html.twig', [
  929.             'entreprise' => $entreprise,
  930.             'contrat' => $contrat,
  931.             'form' => $form->createView(),
  932.         ]);
  933.     }
  934.     /**
  935.      * @Route("/entreprise/{entrepriseId}/delete-contrat/{id}", name="app_entreprise_delete_contrat")
  936.      */
  937.     public function deleteContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $entrepriseIdint $id): Response
  938.     {
  939.         $entreprise $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
  940.         $contrat $doctrine->getRepository(Contrat::class)->find($id);
  941.         if (!$entreprise) {
  942.             throw $this->createNotFoundException('Entreprise not found');
  943.         }
  944.         if (!$contrat) {
  945.             throw $this->createNotFoundException('Contrat not found');
  946.         }
  947.         if ($this->isCsrfTokenValid('delete'.$contrat->getId(), $request->request->get('_token'))) {
  948.             $entityManager->remove($contrat);
  949.             $entityManager->flush();
  950.         }
  951.         return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  952.     }
  953.     private function calculateDurationInMonths(?\DateTimeInterface $dateDebut, ?\DateTimeInterface $dateFin): ?int
  954.     {
  955.         if (!$dateDebut || !$dateFin) {
  956.             return null;
  957.         }
  958.         $interval $dateDebut->diff($dateFin);
  959.         return $interval->12 $interval->m;
  960.     }
  961.     private function getPDLChoicesForEntreprise(ManagerRegistry $doctrineEntreprise $entreprise): array
  962.     {
  963.         $electricMeters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
  964.         $gasMeters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
  965.         $pdlChoices = [];
  966.         foreach ($electricMeters as $meter) {
  967.             $pdlChoices[$meter->getPDL()] = $meter->getPDL();
  968.         }
  969.         foreach ($gasMeters as $meter) {
  970.             $pdlChoices[$meter->getPDL()] = $meter->getPDL();
  971.         }
  972.         return $pdlChoices;
  973.     }
  974.     /**
  975.      * @Route("/entreprise/associate-user", name="app_entreprise_associate_user")
  976.      */
  977.     public function associateUser(Request $requestEntityManagerInterface $entityManager): Response
  978.     {
  979.         $this->denyAccessUnlessGranted('ROLE_COMPTA');
  980.         try {
  981.             $form $this->createForm(UserEntrepriseType::class);
  982.             $form->handleRequest($request);
  983.             if ($form->isSubmitted() && $form->isValid()) {
  984.                 $data $form->getData();
  985.                 $user $data['user'];
  986.                 $entreprises $data['entreprises'];
  987.                 // Vérification des données
  988.                 if (!$user || !$entreprises || empty($entreprises)) {
  989.                     throw new \InvalidArgumentException('Utilisateur et entreprises sont requis');
  990.                 }
  991.                 // Add ROLE_CLIENT_PRO if user doesn't have it
  992.                 if (!$user->hasRole('ROLE_CLIENT_PRO')) {
  993.                     $roles $user->getRoles();
  994.                     $roles[] = 'ROLE_CLIENT_PRO';
  995.                     $user->setRoles(array_unique($roles));
  996.                 }
  997.                 // Associate user with enterprises
  998.                 foreach ($entreprises as $entreprise) {
  999.                     if (!$user->getEntreprises()->contains($entreprise)) {
  1000.                         $user->addEntreprise($entreprise);
  1001.                         $entreprise->addUtilisateur(strval($user->getId()));
  1002.                     }
  1003.                 }
  1004.                 
  1005.                 $entityManager->persist($user);
  1006.                 $entityManager->flush();
  1007.                 $this->addFlash('success'sprintf(
  1008.                     'L\'utilisateur %s a été associé avec succès à %d entreprise(s)',
  1009.                     $user->getUsername(),
  1010.                     count($entreprises)
  1011.                 ));
  1012.                 return $this->redirectToRoute('app_entreprise');
  1013.             }
  1014.             return $this->render('entreprise/associate_user.html.twig', [
  1015.                 'form' => $form->createView(),
  1016.             ]);
  1017.         } catch (\Exception $e) {
  1018.             $this->addFlash('error''Une erreur est survenue lors de l\'association : ' $e->getMessage());
  1019.             return $this->redirectToRoute('app_entreprise_associate_user');
  1020.         }
  1021.     }
  1022. }